Jquery计算2个元素之间的项目

时间:2013-04-12 09:18:24

标签: jquery html

我有一个像这样的HTML树

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

我有一个点击功能,每次选择div类项目中的图像时都会运行,无论如何我可以计算一个项目类别的div的数量是彼此相邻的。

即,如果我在上面的示例中单击“1”,它将返回2,因为在h1之前有2个div,如果我点击第7项,它将返回5等

这可能吗?

由于

4 个答案:

答案 0 :(得分:5)

这对你有用:

$('.item').on('click',function(){
    var h1 = $(this);
    while(!h1.is('h1')) h1 = h1.prev();
    alert(h1.nextUntil('h1').length);
});

DEMO

答案 1 :(得分:2)

$('.item').click(function () {
        alert($(this).prevAll('h1').first().nextUntil('h1').length);

});

JS FIDDLE LINK

答案 2 :(得分:1)

是。您可以计算所有具有班级item的兄弟姐妹:

var count = $(this).siblings('.item').andSelf().length;

(在jQ 1.8及更高版本中你应该使用addBack()而不是andSelf()

jQuery API参考非常有用,建议阅读:

最重要的是选择和遍历方法的两大列表:

答案 3 :(得分:-1)

试试这个

 $(document).ready(function(){
        $('.item').click(function(){

            var title = $(this).prevAll('h1').first();
            var nextElement = title;
            var reachedNextTitle = false;
            var noOfDiv = 0;
            var loopLimit = 1000;
            var count = 0;
            while(!reachedNextTitle){
                count ++;
                nextElement = nextElement.next();
                if(nextElement.is('h1')){
                    reachedNextTitle = true;
                }

                if(nextElement.is('div')){
                    noOfDiv ++;
                }
                if(count > loopLimit){
                    break;
                }
            }

            alert(noOfDiv);
        });
    });
相关问题