[英]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.