indexing - Jquery index can't find element (-1) wrong input (with live function) -
i index of li element. li elements created after page loaded. jquery returns -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 li index:
$("#warp-expand ul li a").live('click',function () { var x = $("warp-expand ul li").index(this); alert(x); //returns -1 });
how li's 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 go:
$('#warp-expand a').live('click',function () { var idx = $(this).closest('li').index(); });
live demo: http://jsfiddle.net/aphrq/1/
so, can see, calling index()
without parameters works fine. select element (in case corresponding li element) , call index()
on it.
also, consider caching dom element reference on page-load:
// cache reference on page-load (do 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/
Comments
Post a Comment