Javascript 找到被点击的 li 号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2927592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find the clicked li number
提问by fire
I have a standard list.
我有一个标准清单。
<ul>
<li><a href="#">blah 1</a></li>
<li><a href="#">blah 2</a></li>
<li><a href="#">blah 3</a></li>
<li><a href="#">blah 4</a></li>
</ul>
And my jQuery:
还有我的 jQuery:
$('ul li a').live('click', function() {
var parent = $(this).parent('li');
});
What I want to find out is the parent li's position in the list of the clicked link e.g. clicking on blah 3 would give me 2, blah 4 would give 3 etc.
我想知道的是父 li 在点击链接列表中的位置,例如点击 blah 3 会给我 2,blah 4 会给 3 等等。
回答by Erik
$('ul li a').live('click', function() {
console.log($(this).parent('li').index());
});
Will give you what you want, but keep in mind these are 0 based indexes -- ie the first line item is index 0, the last line item is 3.
会给你你想要的,但请记住,这些是基于 0 的索引——即第一个项目是索引 0,最后一个项目是 3。
回答by Alex Pacurar
you can get the index of an element with jquery`s index
您可以使用jquery 的索引获取元素的索引
$('ul li a').live('click', function()
{
var index = $(this).index();
});
回答by Arkh
No need to jQueryfy this :
无需对此进行 jQueryfy:
$('ul li a').live('click', function() {
var position = 0;
var currentNode = this;
var firstNode = currentNode.parentNode.firstChild;
while(firstNode != currentNode) {
position++;
currentNode = currentNode.previousSibling;
}
alert(position);
});
回答by Sam Jones
回答by kgiannakakis
$(function() {
$('ul li a').live('click', function() {
var parent = $(this).parent('li');
alert(parent.prevAll('li').size());
});
});

