count number of elements between “this” and “that”

2020-07-14 09:41发布

I'm trying to know how "far" away a clicked element in the DOM is to a certain other element.

<li>item1</li>
<li>item2</li>
<li class="active">item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>

So when a user clicks an element it should return the distance to the active element: So item1: return -2, item4: return 1, item6: return 3, and so on.

标签: jquery
2条回答
混吃等死
2楼-- · 2020-07-14 10:18

I believe you could do it the index() method...

Something like this:

var value = $('li').index() - $('li.active').index();
查看更多
家丑人穷心不美
3楼-- · 2020-07-14 10:20

Here you go:

$( ul ).delegate( 'li', 'click', function () {
    var idx1 = $( this ).index(),
        idx2 = $( this ).siblings().andSelf().filter( '.active' ).index();

    var distance = idx1 - idx2;

    // do stuff with distance
});

Live demo: http://jsfiddle.net/aeEBP/

查看更多
登录 后发表回答