Get each <li> index number with jQuery

跟風遠走 提交于 2019-12-19 03:43:13

问题


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.

On each li click I do this function:

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

Which always give's me 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.

Thanks

How can I alert the li number I choosed?


回答1:


You need to use the this object in the click function.

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



回答2:


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

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

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



来源:https://stackoverflow.com/questions/7479229/get-each-li-index-number-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!