gpt4 book ai didi

javascript - for循环内的jquery.load()不起作用

转载 作者:行者123 更新时间:2023-11-30 16:59:04 24 4
gpt4 key购买 nike

我正在尝试在 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 文件将 header 位置更改为图像的 url,即在这种情况下

http://localhost/plum_final/images/products/SilkHotPinkHibiscus.jpg

注意 base_url 是 http://localhost/plum_final/

直接使用图片加载正常

最佳答案

@Stephen Sarcsam Kamenar 提到的问题与不将 for 循环的内部部分包裹在闭包中有关。

因为 .load 是一个异步事件,传递给 .load 的回调只会在加载其中一个图像时运行。因为它关闭了对图像变量的访问,所以无论图像变量的最新值是什么,都将用作追加的参数。

一个快速的解决方案是将 for 循环的内部逻辑包装在一个显式绑定(bind)的立即调用的函数表达式中。像这样:

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);
}

希望对您有所帮助:)

关于javascript - for循环内的jquery.load()不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29199442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com