Get parent index with jQuery [duplicate]

2019-02-05 19:42发布

This question already has an answer here:

<ul class="bullets">
  <li><a href="#">item 1</a></li>
  <li><a href="#">item 2</a></li>
  <li><a href="#">item 3</a></li>
  <li><a href="#">item 4</a></li>
  <li><a href="#">item 5</a></li>
</ul>

When I click on the <a> element, i'd like to get it's parent <li>'s index number.

I'm trying to create a carrousel type function that doesn't need item-n classes on the list items.

$(".bullets li a").click(function(){

   var myIndex = $(this).parent().index(this);
   showPic(myIndex);

});

Thanks for any help.

TD.

6条回答
来,给爷笑一个
2楼-- · 2019-02-05 20:03

$(this).parent().index();

short and sweet

Correction : this is not short and sweet

from where this comes it should be like:

$(".bullets li a").click(function(){
    var myIndex = $(this).parent().index();
    console.log(myIndex);
    showPic(myIndex);
});
查看更多
姐就是有狂的资本
3楼-- · 2019-02-05 20:03
$(".bullets li a").click(function(){
    var myIndex = $(this).parent().index();
    console.log(myIndex);
    showPic(myIndex);
});
查看更多
SAY GOODBYE
4楼-- · 2019-02-05 20:17
$(".bullets li a").click(function(){

   var myIndex = $(this).parent().prevAll().length;
   showPic(myIndex);

});

Note: prevAll().length will give you a zero-based index; the first item will be 0 (zero).

查看更多
趁早两清
5楼-- · 2019-02-05 20:18
$(".bullets li a").click(function(){
   var me = $(this);
   var myIndex = $.each($("li", $(this).parent().parent()), function(i, item){
      if(item == me){
      showPic(i);
   });
});
查看更多
趁早两清
6楼-- · 2019-02-05 20:24

How I'd do it

$(".bullets li a").click(function()
    {
  var $li = $(this).parent();
  var myIndex = $li.parent().children().index( $li );
  alert( myIndex );
});
查看更多
走好不送
7楼-- · 2019-02-05 20:25

Here is a solution I created using tables. you can see how I used the selectors. Im sure it could be cleaner, but here you are:

    $('.showColumn').live('click',function() {
        var theEl = {{id of the element}};
        var setEl = $('th#' + theEl + '');
        var index = setEl.index(setEl.parentNode);
        $('table tr').each(function() { 
            $('th:eq(' + index + ')',this).show(); 
            $('td:eq(' + index + ')',this).show();
        });
    });

cheers.bo

查看更多
登录 后发表回答