这是我的代码:
<body>
<p id="x"></p>
<p id="y"></p>
<form action="2.php" method="post" name="frm">
<input type="text" name="srch">
</form>
<script>
obj = document.forms["frm"]["srch7"];
obj1 = document.getElementById("noexist");
document.getElementById("x").innerHTML = obj;
document.getElementById("y").innerHTML = obj1;
</script>
</body>
为什么obj返回undefined而obj1返回null, document.forms["frm"]["srch7"];和 document.getElementById("不存在");两者都是对象,必须返回 null,因为元素不存在。
最佳答案
两种情况不同,
obj = document.forms["frm"]["srch7"];
//Here you are trying to access a property that
// is not present under document.forms.frm.
obj1 = document.getElementById("noexist");
//Here it is returning null because getElementById implemented in that way.
// getElementById will return null if the DOM search didn't find any element
// based on the supplied id.
关于javascript - 对象中的 null 和 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37046913/