【发布时间】:2012-06-21 22:03:58
【问题描述】:
我如何知道元素的数量? (使用 Javascript 或 jQuery) 假设我有一个UL,里面有多个LI,我怎么知道点击的LI是第4个还是第6个?
$('li').click(function(){
nth = $(this).nth();
alert(nth);
});
【问题讨论】:
标签: javascript jquery
我如何知道元素的数量? (使用 Javascript 或 jQuery) 假设我有一个UL,里面有多个LI,我怎么知道点击的LI是第4个还是第6个?
$('li').click(function(){
nth = $(this).nth();
alert(nth);
});
【问题讨论】:
标签: javascript jquery
你可以试试nth = $(this).prevAll().count() + 1
【讨论】:
你可以使用索引方法:
var nth = $(this).index()+1;
【讨论】:
$('li').click(function(){
alert($(this).index());
});
【讨论】:
您可以为此使用 jQuery 的 .index。
$("li").click(function() {
var nth = $("ul li").index($(this));
alert(nth);
});
【讨论】:
我做了类似的事情
$('li').each(function (i) {
$(this).data("pos", i);
}).click(function() {
var nth = $(this).data("pos");
alert(nth);
});
我总是需要这个职位来做其他事情,所以我把它留了下来。
【讨论】: