2011-09-20 19 views
1

我想計數的數量不使用類名組給出:計數的div不使用

<div class="item" id="home1">home 1 text here</div> 
<div class="item" id="home2">home 2 text here</div> 
<div class="item" id="home3">home 3 text here</div> 
<div class="item" id="home4">home 4 text here</div> 

我已經試過這

alert($(['id^="home"']).length); 

但它一直給我0

有沒有更適當的方法來做到這一點?

+1

更合適的方法是使用類名。你爲什麼厭惡課? –

+0

該類名在應用程序的其他地方用於計算更大的div組,但不是所有的div。 – oshirowanen

+2

元素可以有多個類'

home 1 text here
' – Dennis

回答

6

語法錯誤,試試這個:

alert($('[id^="home"]').length); 
0

你的單引號是在錯誤的地方。你把它們放在方括號內。他們需要在括號外。

試試這個

alert($('[id^="home"]').length); 

例子:http://jsfiddle.net/jasongennaro/dVtzx/

1

如果您的div處於containin所有的兄弟姐妹g元素你可以做$('.parentClass').find('div').length;

0

我會將div包裹在另一個div中,並給包裝一個id。 然後只在這個包裝中計數div。

<div id="wrapper"> 
    <div class="item" id="home1">home 1 text here</div> 
    <div class="item"id="home2">home 2 text here</div> 
    <div class="item" id="home3">home 3 text here</div> 
    <div class="item" id="home4">home 4 text here</div> 
</div> 

這也會更有效率。因爲它發現#wrapper使用getElementById,然後只運行在它的子代上,而不是在整個文檔的元素上搜索id模式。

alert($("#wrapper .item").length); 
0

你的問題似乎已經解決了(放錯地方的括號),但有一些方法可以選擇除了使用id子元素。

<div id="homeDiv"> 
    <div class="item" id="home1">home 1 text here</div> 
    <div class="item" id="home2">home 2 text here</div> 
    <div class="item" id="home3">home 3 text here</div> 
    <div class="item" id="home4">home 4 text here</div> 
</div> 

JS:

$("#homeDiv .item"); //If they are wrapped in a div, specify that and use descendant selection 

<div class="item home" id="home1">home 1 text here</div> 
<div class="item home" id="home2">home 2 text here</div> 
<div class="item home" id="home3">home 3 text here</div> 
<div class="item home" id="home4">home 4 text here</div> 

JS:

$("div.item.home"); //Elements can have multiple classes 
$(".home"); //And you can use any class name to select them.