javascript
  • html
  • dom
  • 2016-03-01 36 views 0 likes 
    0

    我有一個奇怪的問題,我已經寫了上的jsfiddle工作正常,但當我把它寫在我的HTML沒有任何反應函數...工作在JsFiddle但不在現場的Vanilla Javascript函數?

    var el = document.querySelectorAll(".sp-methods li:first-child"); 
    for (i = 0; i < el.length; i++) { 
        alert('sad') 
        el[i].style.display='none'; 
    } 
    

    我的全HTML是

    <!DOCTYPE html> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <title>Untitled Document</title> 
    <script> 
    /*if(!window.location.href.indexOf("gpf") > 0){ 
        alert('contains gpf, show 4-6 days'); 
    } else {*/ 
        var el = document.querySelectorAll(".sp-methods li:first-child"); 
        for (i = 0; i < el.length; i++) { 
         alert('sad') 
         el[i].style.display='none'; 
        } 
    /*}*/ 
    
    </script> 
    </head> 
    <body> 
    <ul class="sp-methods"> 
        <li class=" ">Hide me</li> 
        <li class=" ">Dont hide me</li> 
        </li> 
    </ul> 
    </body> 
    </html> 
    

    但它在這裏工作,我不知道爲什麼?

    JSFiddle Link

    +0

    'console.log(el.length)'你的代碼工作正常,它只是由於執行代碼時找不到任何元素。 –

    +0

    您的元素尚未加載。正如德米特里所說,在你的元素被聲明之後,把你的代碼*。 –

    +0

    因爲你的小提琴運行onload,並且你的代碼在所有元素加載之前都在頭部運行。這就像在製作披薩之前吃披薩一樣。您需要等待元素訪問它們。因此,將代碼放在主體的末尾,或者在引用的元素之後,或者在文檔準備就緒或者在窗口上啓動後加載 – epascarello

    回答

    1

    將在body標籤後,你的JavaScript代碼(腳本)(UL標籤後)

    0

    你正在運行的腳本在你head時,你有沒有DOM的是,被稱爲render-blocking JavaScript。只需移動它,並將其包裝在ready中即可。請注意以下幾點...

    <body> 
    <ul class="sp-methods"> 
        <li class=" ">Hide me</li> 
        <li class=" ">Dont hide me</li> 
    </ul> 
    <script> 
        document.addEventListener('DOMContentLoaded', function(){ 
         var el = document.querySelectorAll(".sp-methods li:first-child"); 
         for (i = 0; i < el.length; i++) { 
          alert('sad') 
          el[i].style.display='none'; 
         } 
        }, false); 
    </script> 
    </body> 
    

    有幾種方法可以在DOM準備就緒時運行腳本。看到如此質疑pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it - 整整討論這個話題

    JSFiddle Link - 更新小提琴


    作爲一個觀察,您在您的標記有一個額外的收盤</li>

    +0

    汽車解釋downvote?看起來像這裏所有的答案都得到了系列downvoted – scniro

    -1

    我的建議是,你拿看看這篇文章的第一個答案: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

    這裏有兩個問題:

    1)您在代碼之前有腳本,所以DOM沒有準備好。

    2)你的腳本只有一些代碼行,沒有任何東西強迫它被執行。我建議使用IIFE模式(function(){....})()或document.onload Jsfiddle爲你做兩件事,這就是它在那裏工作的原因。

    相關問題