2009-12-14 20 views
10

似乎很簡單,但我無法讓它工作。與某個類別的計數div

我有兩個div與類'用戶'。我想輸出「你有2個div」。

<script type="text/javascript"> 
    $(document).ready(function() { 
     function divcount() { 
      var mycount = $('.user').length(); 
      document.write(mycount) 
     } 
    }); 
</script> 

我敢肯定,我失去了一些東西簡單..

+0

Wess,在使用'document.write'完成DOM完成後,您無法寫入文檔。試試這個:'$(document.body).append(mycount)',然後確保在某處調用你的'divcount()'函數來激活它。 –

+0

應該總是使用'console.log(String);'來調試:)比'document.write'工作要好得多 – Charles

回答

8

Length是屬性不是一個函數。大小是一個功能。

+0

這個鏈接起作用了!謝謝:) – wesbos

10

它可以是$('.user').lengthlength property of Array)或$('.user').size()size method of jQuery)。

+0

我已經嘗試過,我不能讓它輸出文本中的數字。我將如何做到這一點? – wesbos

+0

刪除divcount功能。 –

+0

@Wes:你曾經叫過'divcount'函數嗎? – Gumbo

1

這只是$('.user').length。這是一個屬性,而不是方法調用。

1
$(".user").length // use the length property 

$(".user").size() // use the size method 

注意代碼必須包含在$(function(){...})塊中;例如:

$(function(){ 
    alert($(".user").length); 
    alert($(".user").size()); 
}); 
相關問題