Jquery索引找不到元素(-1)错误输入(带有live函数) [英] Jquery index can't find element (-1) wrong input (with live function)

查看:142
本文介绍了Jquery索引找不到元素(-1)错误输入(带有live函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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>

获取li指数的Jquery:

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  

 });

li如何制作:

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

});


推荐答案

在这里:

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

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

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

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.

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

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

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

这篇关于Jquery索引找不到元素(-1)错误输入(带有live函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆