Jquery索引可以';找不到元素(-1)输入错误(带活动功能)

Jquery索引可以';找不到元素(-1)输入错误(带活动功能),jquery,indexing,live,Jquery,Indexing,Live,我想得到li元素的索引。li元素是在加载页面后创建的。Jquery返回一个-1未找到错误 结构html(可在dom中找到,而不是在页面源代码中找到): 李的制作方法: $("#playlister").click(function () { $("#jp_playlist_2 ul li").each(function() { var s = $(this).text(); $('#warp-expand ul').append('<li><d

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

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

李的制作方法:

 $("#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>');
    });

});
$(“#播放列表”)。单击(功能(){
$(“#jp_播放列表_2 ul li”)。每个(函数()
{
var s=$(this.text();
$(“#扭曲扩展ul”).append(“
  • ”+s+”
  • ”); }); });
    给你:

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

    因此,正如您所看到的,在没有任何参数的情况下调用
    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();        
    });
    

    现场演示:

    您缺少索引函数的
    #warp expand
    。@Scurker:请将此作为一个答案发布,这也是一个有用的答案。谢谢你对效率的建议。
     $("#warp-expand ul li a ").live('click',function () {
    
        var x = $(this).closest('li').index();
        alert(x); 
    
     });
    
    $('#warp-expand a').live('click',function () {    
        var idx = $(this).closest('li').index();    
    });
    
    // 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();        
    });