单击内部链接时列表项ul li的索引 [英] Index of list item ul li when click on link inside

查看:98
本文介绍了单击内部链接时列表项ul li的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了很多有关获取索引价值的问题.

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

我知道如何获得点击索引号上的li.但是,单击其中的链接时,我需要获取li值.

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)
});

它将不起作用,因为它采用的是a.link而不是ul li的索引.单击特定的a.link时如何获取li的索引?

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?

推荐答案

您可以使用jQuery的 parent( ) 选择器,以定位所单击的锚链接的父元素的索引.

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

在这种情况下,它将是:$(this).parent().index();.

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);
});

这篇关于单击内部链接时列表项ul li的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆