开发者

Jquery index can't find element (-1) wrong input (with live function)

I like to get the index of the li element. The li elements are created after the page loaded. Jquery returns a -1 not found error.

The structure html (found in dom, not in page source):

<div id="warp-expand">
  <ul>
   <li><div class="song"><div class="list_b"></div><a>test1</a></div></li>
   <li><div class="song"><div class="list_b"></div><a>test2</a></div></li>
 开发者_运维问答 </ul>
</div>

Jquery to get the li index:

 $("#warp-expand ul li a").live('click',function () {

    var x = $("warp-expand ul li").index(this);
    alert(x); //returns -1  

 });

How the li's are made:

 $("#playlister").click(function () {
    $("#jp_playlist_2 ul li").each(function()
    {
    var s = $(this).text();
    $('#warp-expand ul').append('<li><div class="song"><div class="list_b"></div><a>' +s+ '</a></div></li>');
    });

});


Here you go:

$('#warp-expand a').live('click',function () {    
    var idx = $(this).closest('li').index();    
});

Live demo: http://jsfiddle.net/Aphrq/1/

So, as you can see, calling index() without any parameters works just fine. Just select the element (in this case the corresponding LI element) and call index() on it.


Also, consider caching your DOM element reference on page-load:

// cache reference on page-load (do this for all your references)
var warp = $('#warp-expand');

// use delegate(), it's better!
warp.delegate('a', 'click', function() {
    var idx = $(this).closest('li').index();        
});

Live demo: http://jsfiddle.net/Aphrq/2/


 $("#warp-expand ul li a ").live('click',function () {

    var x = $(this).closest('li').index();
    alert(x); 

 });

http://jsfiddle.net/5vGsE/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜