[英]When document.getElementByID is used without an ID what is it doing?
我正在查看一些代码,该代码在getElementByID上使用了一个我不理解的变体。 我在网上看过,但找不到任何可以解释这一点的东西。
我了解如何使用诸如document.getElementByID(“ bob”)之类的东西,但是我正在查看的内容是:
if (document.getElementByID){}
当您以这种方式使用getElementByID时,它在做什么?
document.getElementById
返回可以用于通过ID获取某些元素的函数。
typeof document.getElementById; // 'function'
但是,如果某些浏览器未实现getElementById
,则会得到undefined
。
因此,这只是确保该方法在调用之前存在的一种测试,从而避免了错误。
if(document.getElementById) {
// Hopefully it's safe to call it
document.getElementById("bob");
// ...
} else {
alert('What kind of stupid browser are you using? Install a proper one');
}
这将返回false
:
if (document.getElementByID){}
因为document
对象上没有getElementByID
。 但是,有getElementById
(注意d
末尾的差异)。
因此,这将返回true
if (document.getElementById){}
简而言之,如果getElementByID
存在于文档中(由于键入而不会),但是如果存在,则执行某些操作。
使用正确拼写的更完整示例:
if (document.getElementById) {
// it is safe to use this method because it exists on document
var element = document.getElementById('foo');
}
document.getElementById
返回一个函数,该函数在表达式中时结果为true
。 您可以自己测试一下,但是运行代码片段。
console.log(document.getElementById); // The !! forces a boolean console.log(!!document.getElementById);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.