javascript - jQuery each 太快了

标签 javascript jquery for-loop each

我正在尝试将属性 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/

相关文章:

javascript - 如何获取在 Node 中调用函数的文件名和行号?

javascript - 检查 Busboy 完成事件是否已经发生

javascript - 如何根据对象值从两个数组创建一个新的对象数组?

带有关键字 : 'this' 的 jQuery悬停函数

c++ - i < N+1 和 i <= N 不同吗?

javascript - 在类范围之外触发​​事件 javascript

jquery 幻灯片自动播放,带有下一个和上一个项目缩略图

javascript - 当用户停止点击时触发事件

c++ - 如何在 C++ 的一个项目中访问所有具有相同类型/类的对象?

python - 结果为 append 到列表的多处理 for 循环