问题描述
我在这里阅读了很多有关获取索引价值的问题.
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的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!