[英]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.