Jquery索引找不到元素(-1)错误输入(带有live函数)

我想得到li元素的索引。 li元素在页面加载后创建。 Jquery返回-1未找到错误。

结构html(在dom中找到,而不是在页面源中):

 

Jquery获取li索引:

  $("#warp-expand ul li a").live('click',function () { var x = $("warp-expand ul li").index(this); alert(x); //returns -1 }); 

如何制作李:

  $("#playlister").click(function () { $("#jp_playlist_2 ul li").each(function() { var s = $(this).text(); $('#warp-expand ul').append('
  • '); }); });

    干得好:

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

    现场演示: http //jsfiddle.net/Aphrq/1/

    所以,正如你所看到的,调用没有任何参数的index()就可以了。 只需选择元素(在本例中为相应的LI元素)并在其上调用index()


    另外,请考虑在页面加载时缓存DOM元素引用:

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

    现场演示: 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/