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