使用 jQuery 获取每个 <li> 索引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7479229/
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-26 23:54:45  来源:igfitidea点击:

Get each <li> index number with jQuery

jqueryindexing

提问by jQuerybeast

I'm trying to get the index number of few <li>'s. The li's are 8 and I'm trying to get each li's number.

我正在尝试获取 some 的索引号<li>。li 是 8,我正在尝试获取每个 li 的号码。

On each li click I do this function:

在每次 li 单击时,我执行此功能:

var str = $('#amastorage li').index();
alert(str);

Which always give's me 8.

这总是给我 8。

EDIT:

编辑:

This is how I get it:

这就是我得到它的方式:

$("#amastorage ul").find('a').click(function () {
        var str = $('#amastorage li').index();
        alert(str);
});

I cant change: $("#amastorage ul").find('a').click(function () {because It's from a plugin and it won't work.

我无法更改:$("#amastorage ul").find('a').click(function () {因为它来自插件并且无法正常工作。

Thanks

谢谢

How can I alert the li number I choosed?

如何提醒我选择的li号码?

回答by Joseph Marikle

You need to use the thisobject in the click function.

您需要this在单击功能中使用该对象。

http://jsfiddle.net/kuJWc/

http://jsfiddle.net/kuJWc/

$("li").click(function(){
    var str = $(this).index();
    alert(str);
});

per your edit:

根据您的编辑:

$("#amastorage ul").find('a').click(function () {
        var str = $(this).parents("li").index();
        alert(str);
});

回答by bittersweetryan

You'll want to loop through all the children of the ul and assign a click handler to each li like so:

您需要遍历 ul 的所有子项并为每个 li 分配一个单击处理程序,如下所示:

$("#amastorage").children().each(function(i){
    $(this).click(function(){
        var index = i;
        alert(index);
    });
});

Here's an example in action: http://jsfiddle.net/qAuUe/

这是一个实际示例:http: //jsfiddle.net/qAuUe/