簡體   English   中英

如何獲取未使用javascript渲染的dom元素?

[英]How do I get the dom element which has not rendered with javascript?

我有一個簡單的js代碼:

<html>
<head>
    <title>test</title>

    <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript">
        console.log(document.querySelector('#nav-toggle')); // this will get null
        console.log($('#nav-toggle')); // this will get the element
    </script>
</head>
<body>
    <a id="nav-toggle" href="#">link</a>

    <script type="text/javascript">
        console.log(document.querySelector('#nav-toggle')); // this will get the element
        console.log($('#nav-toggle')); // this will get the element
    </script>
</body>
</html>

正如我評論的那樣,第一個document.querySelector('#nav-toggle')將獲取null ,我猜問題是dom element尚未呈現,因為第二個獲取了元素。

但是jQuery不管位置如何都可以獲取元素, jQuery如何做到這一點?

有很多不同的方法可以檢查事物是否已滿載。 哪種方法應該始終基於您的需要。 您不想等待的時間超過實際需要的時間。

需要澄清的是,“ window.load”與jQuery的“ $(document).ready()” 並不相同。

如果您想使用“香草”替代品,則可以使用DOMContentLoaded。

DOMContentLoaded

從MDN: https//developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

當文檔已完全加載和解析時,將觸發DOMContentLoaded事件,而無需等待樣式表,圖像和子幀完成加載(可以使用load事件來檢測完全加載的頁面)。

document.addEventListener("DOMContentLoaded", function() {
});

window.load

從MDN: https//developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload

加載事件在文檔加載過程結束時觸發。 至此,文檔中的所有對象都在DOM中,並且所有圖像,腳本,鏈接和子框架均已完成加載。

window.onload = function() {
}

你被誤導了。 jQuery無法獲取尚不存在的元素。 jQuery可以使用其document.ready方法,該方法在文檔加載后運行。 您可以使用onload事件在香草javascript中獲得類似的結果。

將您的代碼更改為以下代碼,如果DOM中存在該元素,您將始終找到該元素

<html>
<head>
    <title>test</title>

    <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript">
        window.onload = function() {
          console.log(document.querySelector('#nav-toggle')); // this will get null
          console.log($('#nav-togglle')); // this will get the element
    }
    </script>
</head>
<body>
    <a id="nav-toggle" href="#">link</a>

    <script type="text/javascript">
        console.log(document.querySelector('#nav-toggle')); // this will get the element
        console.log($('#nav-togglle')); // this will get the element
    </script>
</body>
</html>

只是為了解釋,jQuery並沒有在其中發揮任何作用。 為了進行測試,您可以交換原始的javascript和jquery代碼行,通過刷新頁面嘗試幾次,您可能會看到不同的結果。

在您當前的情況下,只是jQuery可以找到該元素,因為該元素是在調用jQuery語句之前加載的(異步性質,您會看到的!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM