开发者

Find the clicked li number

I have a standard list.

<ul>
  <li><a href="#">blah 1</a></li>
  <li><a href="#">blah 2</a></li>
  <li><a href="#">blah 3</a></li>
  <li><a href="#">blah 4</a></li>
</ul>

And my jQuery:

$('ul li a').live('click', function() {
  var parent = $(this).parent('li');
});

What I want to find out is the parent li's position in the lis开发者_如何学Got of the clicked link e.g. clicking on blah 3 would give me 2, blah 4 would give 3 etc.


$('ul li a').live('click', function() {
    console.log($(this).parent('li').index());
});

Will give you what you want, but keep in mind these are 0 based indexes -- ie the first line item is index 0, the last line item is 3.

jQuery index() method documentation


you can get the index of an element with jquery`s index

$('ul li a').live('click', function() 
{
    var index =  $(this).index();
});    


No need to jQueryfy this :

$('ul li a').live('click', function() {
    var position = 0;
    var currentNode = this;
    var firstNode = currentNode.parentNode.firstChild;
    while(firstNode != currentNode) {
        position++;
        currentNode = currentNode.previousSibling;
    }
    alert(position);
});


I know this is an old post, but .live is now deprecated in jQuery 1.7 and removed in jQuery 1.9.

The alternative is to use .delegate:

$('ul li').delegate('a','click', function() {

    alert($(this).parent('li').index());

});


The index method should do what you want.


$(function() {
    $('ul li a').live('click', function() {
        var parent = $(this).parent('li');
        alert(parent.prevAll('li').size());
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜