[英]jquery.load() inside a for loop not working
我正在嘗試在for循環中使用jquery的,load函數將圖像加載到我的產品目錄中,該圖像的URL由php腳本返回
var limit=12;
for (var count=1;count<=limit;count++) {
var img = $("<img />").attr('src', 'includes/ajax/getimgurl.php?pid='+count)
.load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#product_img_"+count).append(img);
}
});
}
php文件返回將標題位置更改為圖像的url,在這種情況下
HTTP://localhost/plum_final/images/products/SilkHotPinkHibiscus.jpg
請注意,base_url是http:// localhost / plum_final /
在直接使用加載時,圖像加載正常
@Stephen Sarcsam Kamenar提到的問題與未將for循環的內部包裝在閉合中有關。
由於.load是一個異步事件,因此傳遞給.load的回調僅在加載其中一個圖像時運行。 因為它結束了對image變量的訪問,所以無論image變量的最新值是什么,都將用作添加的參數。
一種快速的解決方案是將for循環的內部邏輯包裝在顯式綁定的立即調用的函數表達式中。 像這樣:
var limit=12;
for (var count=1;count<=limit;count++) {
(function (count) {
var img = $("<img />").attr('src', 'includes/ajax/getimgurl.php?pid='+count)
.load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#product_img_"+count).append(img);
}
});
})(count);
}
希望有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.