如何索引jquery中的每个元素

时间:2016-05-06 13:29:58

标签: javascript jquery

我需要为每个元素编制索引,如1/8,2 / 8,3 / 8

$(document).ready(function () {

    var Thumbnail = $('.thm-img'); // main image wrapper

    function ThumbnailCounter() {

        var AllNumber = $(Thumbnail).length;

        $(Thumbnail).each(function () {
            var CurrentActive = $(Thumbnail).index() + 1; //return current number active thumbnail
            $(this).children('span').append(CurrentActive  + '/' +  AllNumber);
        });
    }

    new ThumbnailCounter();

});
.thm-img {
  border: 1px solid red;
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="thumb-wrp scrollbar-inner">
  <div class="thm-img">
    <img src="../img/img/a.jpg"><span class="numeric active"></span>
  </div>
  <div class="thm-img">
    <img src="../img/img/b.jpg"><span class="numeric"></span>
  </div>
  <div class="thm-img">
    <img src="../img/img/c.jpg"><span class="numeric"></span>
  </div>
  <div class="thm-img">
    <img src="../img/img/d.jpg"><span class="numeric"></span>
  </div>
  <div class="thm-img">
    <img src="../img/img/a.jpg"><span class="numeric"></span>
  </div>
  <div class="thm-img">
    <img src="../img/img/c.jpg"><span class="numeric"></span>
  </div>
  <div class="thm-img">
    <img src="../img/img/b.jpg"><span class="numeric"></span>
  </div>
  <div class="thm-img">
    <img src="../img/img/d.jpg"><span class="numeric"></span>
  </div>
</div>

3 个答案:

答案 0 :(得分:1)

只需更改脚本:

function ThumbnailCounter() {
        var AllNumber = $(Thumbnail).length;
        $('.thm-img').each(function () {
            var CurrentActive = $(this).index() + 1; // Use $(this) to reference to current element - it will give you right index
            $(this).children('span').append(CurrentActive  + '/' +  AllNumber);
        });
    }

    new ThumbnailCounter();

答案 1 :(得分:1)

你可以使用,

$(".thumb-wrp .thm-img").each(function() {
  var index = $(".thumb-wrp .thm-img").index(this) + 1;
  var total = $(".thumb-wrp .thm-img").length;
  $(this).find("span").text(index + "/" + total);
})

Fiddle

答案 2 :(得分:1)

尝试

 var CurrentActive = $(this).index() + 1;