我怎么知道元素的数量?(使用 Javascript 或 jQuery)假设我有一个带有多个 LI 的 UL,我怎么知道点击的 LI 是第 4 个还是第 6 个?
$('li').click(function(){
nth = $(this).nth();
alert(nth);
});
我怎么知道元素的数量?(使用 Javascript 或 jQuery)假设我有一个带有多个 LI 的 UL,我怎么知道点击的 LI 是第 4 个还是第 6 个?
$('li').click(function(){
nth = $(this).nth();
alert(nth);
});
$('li').click(function(){
alert($(this).index());
});
您可以使用索引方法:
var nth = $(this).index()+1;
你可以试试nth = $(this).prevAll().count() + 1
我做类似的事情
$('li').each(function (i) {
$(this).data("pos", i);
}).click(function() {
var nth = $(this).data("pos");
alert(nth);
});
总是,我最终需要这个职位来做其他事情,所以我把它留了下来。