Index of list item ul li when click on link inside

你离开我真会死。 提交于 2019-12-24 12:57:14

问题


I was reading a lot of questions here about getting value of index.

I know how to get li on click index number. However, I need to get the li value when the link within it is clicked.

<ul>
   <li><a class=link href="#"></a></li>
   <li><a class=link href="#"></a></li>
   <li><a class=link href="#"></a></li>
   <li><a class=link href="#"></a></li>
</ul>


$("li a.link").click(function(e) {
    var i = $(this).index();
       alert(i)
});

It won't work because it takes the index of a.link not ul li. How can I get index of the li when a specific a.link is clicked?


回答1:


You can use jQuery's parent() selector to target the index of the parent element of the clicked anchor link.

In this case, it would be: $(this).parent().index();.

$("li a.link").click(function(e) {
    var i = $(this).parent().index();
    alert(i);
});

If you want to get the physical number (e.g. first returns one, second returns two), you'd just add one to the selector:

$("li a.link").click(function(e) {
    var i = $(this).parent().index() + 1;
    alert(i);
});



回答2:


There are two approaches you can take: count which position the clicked li is, or number them beforehand. The second is much more efficient (constant time on a click):

var li_elems = $('li.link'),
    i = 0,
    len = li_elems.length;

for (; i < len; i++) {
   li_elems[i].attr('index', i);
}

$('ul').on('click', 'li.link', function (e) {
  var index = this.getAttribute('index');
  alert(index);
});


来源:https://stackoverflow.com/questions/16778214/index-of-list-item-ul-li-when-click-on-link-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!