在我的代码中,我看到这个:
if (document.getElementById('xx') !=null) {
//do stuff
}
如果xx
元素未定义,这个表达式会被计算为真还是假?应该写:
if (document.getElementById('xx'))
如何保持安全?
在我的代码中,我看到这个:
if (document.getElementById('xx') !=null) {
//do stuff
}
如果xx
元素未定义,这个表达式会被计算为真还是假?if (document.getElementById('xx'))
如何保持安全?
console.log(document.getElementById('xx') ) evaluates to null.
document.getElementById('xx') !=null evaluates to false
你应该使用 document.getElementById('xx') !== null
,因为它是一种更强的相等性检查方法。
console.log
! - jaygetElementById
被DOM Level 1 HTML定义用于在没有匹配元素的情况下返回null
。
!==null
是最明确的检查形式,也可能是最好的形式,但是getElementById
不能返回非null
的falsy值,你只能得到null
或始终为真的Element对象。所以在这里!==null
, !=null
或更宽松的if(document.getElementById('xx'))
之间没有实际区别。
getElementById
返回的唯一假值是null
,如果你只想检查存在性,就没有理由检查任何其他值。 - cowbert如果没有找到,它将返回null,您可以在演示中尝试以下内容。这两个都将返回true。第一个元素存在,第二个不存在。
Html
<div id="xx"></div>
Javascript:
if (document.getElementById('xx') !=null)
console.log('it exists!');
if (document.getElementById('xxThisisNotAnElementOnThePage') ==null)
console.log('does not exist!');
document.getElementById('xx')
将返回undefined
。 - Khanh Trannull
。在控制台中测试一下。 - Denys Séguretnull
。 - raina77ow