jQuery计数2个元素之间的项目 [英] Jquery count items between 2 elements
本文介绍了jQuery计数2个元素之间的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一棵这样的HTML树
I have an HTML tree like this
<div class="container">
<h1>title</h1>
<div class="item">1</div>
<div class="item">2</div>
<h1>title</h1>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<h1>title</h1>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
我有一个click函数,每次在div类项中选择一个图像时,该函数就会运行,无论如何我可以算出与某类项相邻的div数.
I have a click function that runs everytime an image within a div class item is selected, is there anyway I can count the number of divs with a class of item are next to each other.
即,如果我在上面的示例中单击"1",它将返回2,因为h1之前有2个div,如果我单击了项7,则将返回5等等
ie, if I clicked on '1' in my example above, it would return 2, because there are 2 divs before the h1, if I clicked on item 7, it would return 5 etc
有可能吗?
谢谢
推荐答案
这将为您工作:
$('.item').on('click',function(){
var h1 = $(this);
while(!h1.is('h1')) h1 = h1.prev();
alert(h1.nextUntil('h1').length);
});
这篇关于jQuery计数2个元素之间的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文