简体   繁体   中英

jQuery each is too fast

I'm trying to add attribute data-size to my parent div .

Here is my code:

var width, height;
$(".galerie img").each(function() {
  width = this.naturalWidth;
  height = this.naturalHeight;
  $(this).parent().attr('data-size', width+'x'+height);
});

I have around 40 pictures on 1 page. On this way, not every of my div get 'data-size'. Sometimes only 1/2 of them, sometimes 1/3 of them or only 5 of them. How can I fix it?

use document.ready in window.load. this is because not every images are loaded properly before each function fires

$(window).on("load", function() {
var width, height;
    $(document).ready(function(){
        $(".galerie img").each(function() {
          width = this.naturalWidth;
          height = this.naturalHeight;
          $(this).parent().attr('data-size', width+'x'+height);
        });
    });
});

Use a new Image() and wait for it's onload

var width,
    height;
$(".galerie img").each(function() {
  var $that = $(this);
  var img = new Image();
  img.onload = function(){
     width = this.naturalWidth;
     height = this.naturalHeight;
     $that.parent().attr('data-size', width+'x'+height);
  });
  img.src = this.src;
});

I think the problem is that you are triggering the each when the images are not loaded. Maybe you should check if the last one is loaded before doing it

try to check it with something like this:

 if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {

or the imagesLoaded javascript library.

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