列表中有多少个元素,单击了元素的索引

时间:2014-03-27 14:35:40

标签: jquery

考虑以下标记

<ul id="thumbs">
    <li><a href=""><img class="thumb" src=""></a></li>
    <li><a href=""><img class="thumb" src=""></a></li>
    <li><a href=""><img class="thumb" src=""></a></li>
</ul>

当我点击带有&#39;拇指&#39;的img时,我想要以下内容:

ul列表中有多少列表项目 单击的img所属的列表项的索引

$('img.thumb').click(function(e) {
    // how many elements in the list 'thumbs'

    // the index of the <li> where the img clicked belong to
});

3 个答案:

答案 0 :(得分:3)

您可以使用length获取列表项的总数以及 .closest() .index() 来获取索引被点击图片的最近祖先li

$('img.thumb').click(function(e) {
    // how many elements in the list 'thumbs'
    var length = $('#thumbs li').length;

    // the index of the <li> where the img clicked belong to
    var index = $(this).closest('li').index();
});

<强> Fiddle Demo

答案 1 :(得分:1)

尝试

$('img.thumb').click(function(e) {
  $("#thumbs li").length;
  $(this).closest("li").index();
});

您可以使用closest("li")parents("li")来获取父li目的。您可以使用index()方法找到索引。和length()获取计数

答案 2 :(得分:1)

试试这个:

  $('img.thumb').click(function(e) {
   // how many elements in the list 'thumbs'
     alert($('#thumbs li').length);
   // the index of the <li> where the img clicked belong to
     alert($(this).closest('li').index());
});