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

你。 提交于 2019-12-13 01:28:47

问题


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

});

回答1:


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/




回答2:


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

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

 });

http://jsfiddle.net/5vGsE/



来源:https://stackoverflow.com/questions/6540864/jquery-index-cant-find-element-1-wrong-input-with-live-function

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