在你提供的代码中,对输入进行了 JSON.stringify(),它会将输入值转换为字符串。因此,在解析之前你需要先移除这一行:
const userInput = JSON.stringify(inputElement.value);
然后可以直接使用 inputElement.value 来获取输入的值,并进行判断。修改后的代码如下:
<div>
<input type="text" id="myInput">
</div>
<script>
const inputElement = document.getElementById("myInput");
inputElement.addEventListener("blur", function() {
const userInput = inputElement.value;
console.log(typeof(userInput), 'duhao____Str');
var obj = JSON.parse(userInput);
console.log(obj, 'duhao_____obj');
if (typeof obj === 'object' && obj) {
alert('是json对象');
} else {
alert('不是json对象');
}
});
</script>
现在,当输入 {“name”:“1111”} 时,应该会显示是一个 JSON 对象。
内容由零声教学AI助手提供,问题来源于学员提问