简体   繁体   English

单击链接里面的列表项索引的索引

[英]Index of list item ul li when click on link inside

I was reading a lot of questions here about getting value of index. 我在这里读了很多关于获得指数价值的问题。

I know how to get li on click index number. 我知道如何让li上点击索引号。 However, I need to get the li value when the link within it is clicked. 但是,我需要在单击其中的链接时获取li值。

<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 . 它不起作用,因为它需要a.link的索引而不是ul li How can I get index of the li when a specific a.link is clicked? 如何在点击特定的a.link时获取li索引?

You can use jQuery's parent() selector to target the index of the parent element of the clicked anchor link. 您可以使用jQuery的parent()选择器来定位单击的锚链接的父元素的索引。

In this case, it would be: $(this).parent().index(); 在这种情况下,它将是: $(this).parent().index(); .

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

If you want to get the physical number (eg 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);
});

There are two approaches you can take: count which position the clicked li is, or number them beforehand. 您可以采取两种方法:计算所点击的li的位置,或预先对它们进行编号。 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM