簡體   English   中英

布爾問題

[英]Boolean question

因此,我正在一些書的幫助下自學jQuery,而目前,我被一個看似簡單的問題所困擾。 為什么$('div.foo').length$('div.foo').length 0? 頁面中存在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>
 document.write($(div.foo).length) 

應該

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

而且,您的scipt將在加載DOM之前運行,因此請嘗試將JavaScript封裝在jQuery的$(document).ready -請參見http://docs.jquery.com/Tutorials%3AIntroducing_%24(document).ready( )

您缺少引號

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

編輯:

布拉德說得很對。 您應該將此調用包裝在document.ready

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

很簡單:尚未加載DOM。

您有兩種選擇:

  1. 將代碼放在</body>標記之前,以便已加載文檔元素,因此jQuery可以看到該對象。
  2. 使用$(document).ready(function(){ ...code... }) (或簡寫$(function(){ ...code... })使花括號中的代碼僅在文檔已加載。

嘗試以下兩種選擇尺寸:

重新排序執行程序:

<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>

您必須在創建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
    });

未加載DOM。 采用

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

暫無
暫無

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

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