3

我怎么知道元素的数量?(使用 Javascript 或 jQuery)假设我有一个带有多个 LI 的 UL,我怎么知道点击的 LI 是第 4 个还是第 6 个?

$('li').click(function(){
    nth = $(this).nth();
    alert(nth);
});
4

5 回答 5

6

.index您可以为此使用 jQuery 。

​$("li").click(function() {
    var nth = $("ul li").index($(this));
    alert(nth);
});​

活生生的例子

于 2012-06-19T19:46:44.210 回答
2
$('li').click(function(){
    alert($(this).index());
});
于 2012-06-19T19:46:37.100 回答
1

您可以使用索引方法:

var nth = $(this).index()+1;
于 2012-06-19T19:45:33.307 回答
1

你可以试试nth = $(this).prevAll().count() + 1

于 2012-06-19T19:44:08.537 回答
0

我做类似的事情

$('li').each(function (i) {
  $(this).data("pos", i);
}).click(function() {
  var nth = $(this).data("pos");
  alert(nth);
});

总是,我最终需要这个职位来做其他事情,所以我把它留了下来。

于 2012-06-19T19:47:47.610 回答