简体   繁体   中英

how to index each element in jquery

I need to index each element like this 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> 

Just change your script:

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();

You can use,

$(".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

尝试

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM