我正在尝试将属性 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);
});
});
});
关于javascript - jQuery each 太快了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34297785/