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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:32:33  来源:igfitidea点击:

Find the clicked li number

javascriptjquery

提问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。

jQuery index() method documentation

jQuery index() 方法文档

回答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

I know this is an old post, but .liveis now deprecated in jQuery 1.7 and removed in jQuery 1.9.

我知道这是一篇旧帖子,但.live现在在 jQuery 1.7 中已弃用并在 jQuery 1.9 中删除。

The alternative is to use .delegate:

另一种方法是使用.delegate

$('ul li').delegate('a','click', function() {

    alert($(this).parent('li').index());

});

回答by Edward Dale

The indexmethod should do what you want.

指数的方法应该做你想要什么。

回答by kgiannakakis

$(function() {
    $('ul li a').live('click', function() {
        var parent = $(this).parent('li');
        alert(parent.prevAll('li').size());
    });
});