[英]jQuery each is too fast
我正在尝试将属性data-size
添加到我的父div
。
这是我的代码:
var width, height;
$(".galerie img").each(function() {
width = this.naturalWidth;
height = this.naturalHeight;
$(this).parent().attr('data-size', width+'x'+height);
});
我在一页上有40张照片。 这样,并不是我的每个div都获得“数据大小”。 有时只有其中的1/2,有时是1/3,或者只有5。 我该如何解决?
在window.load中使用document.ready。 这是因为并非每个图像在每个函数触发之前都已正确加载
$(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);
});
});
});
使用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;
});
我认为问题在于,当未加载图像时,您正在触发每个图像。 也许您应该先检查最后一个是否已加载
尝试用类似以下的方法检查它:
if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.