2011-03-08 66 views
0

所以,我正在一些書的幫助下自學jQuery,目前我被一個看似簡單的問題難住了。爲什麼$('div.foo').length的值爲0? A div元素存在於頁面中,爲什麼$('div.foo').length的值不是1?布爾問題

<!DOCTYPE html> 
<html> 
<head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"> 
     </script> 
     <script type="text/javascript"> 
      document.write($(div.foo).length); 
      </script> 
    <body> 
      <div class="foo"></div> 
    </body> 
</html> 

回答

0

簡單包裝這個召喚:DOM還沒有加載。

你有兩個選擇:

  1. 地方</body>標記,以便文檔元素已經加載,因此,jQuery有對象的知名度之前的代碼。
  2. 使用$(document).ready(function(){ ...code... })(或短手$(function(){ ...code... })因此,只有文件被加載後執行大括號中的代碼

嘗試這兩對大小:

重新排序executon:

<html> 
    <head> 
    <script src="jquery.js"></script> 
    </head> 
    <body> 
    <div class="foo"> 
    <script> 
     alert($('.foo').length); 
    </script> 
    </body> 
</html> 

等待加載DOM *

<html> 
    <head> 
    <script src="jquery.js"></script> 
    <script> 
     $(document).ready(function(){ 
     alert($('.foo').length); 
     }); 
    </script> 
    </head> 
    <body> 
    <div class="foo"> 
    </body> 
</html> 
1

你缺少引號

document.write($("div.foo").length); 

編輯:

布拉德使得一個好點。你應該在document.ready

$(document).ready(function() { 
    document.write($("div.foo").length); 
}); 
+0

雖然你說得對,報價並沒有完全加載。它仍然不會看到這個元素。 – 2011-03-08 06:04:27

+0

@Brad:編輯添加更多信息。謝謝 – 2011-03-08 06:09:26

+0

@MaheshValega:不客氣。 ;-) – 2011-03-08 06:10:47

0

你必須在dom元素創建後移動此代碼,通過在body標記之前將其移動到底部。目前,您甚至在DOM中創建元素之前嘗試訪問元素。

<script type="text/javascript"> 
     document.write($('div.foo').length); 
    </script> 

運行代碼後DOM準備就緒,即所有的元素都在DOM創建。

//this piece of code can be placed even before elements are created 
    $(function(){ 
    //this code here, will run after DOM is ready 
    }); 
0

DOM未加載。使用

$(document).ready(function() { 
      alert($('div.foo').length); 
    });