我试图在不使用类名的情况下计算组中的给定数量:
<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
有没有更合适的方法来做这件事?
语法错误,试试这个:
alert($('[id^="home"]').length);
如果div都是包含元素中的兄弟元素你可以使用$('.parentClass').find('div').length;
你的单引号放错地方了。它们在方括号里。
Try this
alert($('[id^="home"]').length);
例子: http://jsfiddle.net/jasongennaro/dVtzx/
你选择错了
alert($("[id^='home']").length);
http://jsfiddle.net/zPBv5/我会将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>
这也会更有效率。因为它使用getElementById
找到#wrapper
,然后只在它的子元素上运行,而不是在整个文档的元素上运行,搜索id模式。
alert($("#wrapper .item").length);
您的问题似乎已经解决(括号错位),但除了使用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.