[英]jQuery each is too fast
I'm trying to add attribute data-size
to my parent div
. 我正在尝试将属性
data-size
添加到我的父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. 我在一页上有40张照片。 On this way, not every of my div get 'data-size'.
这样,并不是我的每个div都获得“数据大小”。 Sometimes only 1/2 of them, sometimes 1/3 of them or only 5 of them.
有时只有其中的1/2,有时是1/3,或者只有5。 How can I fix it?
我该如何解决?
use document.ready in window.load. 在window.load中使用document.ready。 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
使用
new Image()
并等待其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. 或imagesLoaded javascript库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.