开发者

Get each <li> index number with jQuery

开发者 https://www.devze.com 2023-04-05 20:08 出处:网络
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.

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 () { b开发者_StackOverflowecause It's from a plugin and it won't work.

Thanks

How can I alert the li number I choosed?


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


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号