jQuery每一个都太快了
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都得到了'data-size'。有时只有 1/2,有时只有 1/3 或只有 5 个。我该如何解决?
我认为问题在于您在未加载图像时触发了 each。也许你应该在做之前检查最后一个是否加载
尝试用这样的方式检查它:
if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
在 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;
});
我正在尝试将属性 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都得到了'data-size'。有时只有 1/2,有时只有 1/3 或只有 5 个。我该如何解决?
我认为问题在于您在未加载图像时触发了 each。也许你应该在做之前检查最后一个是否加载
尝试用这样的方式检查它:
if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
在 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;
});