for循环中的jquery.load()不起作用


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

请注意,baseurl是http://localhost/plum_final/

直接使用图像加载良好的

@Stephen Sarcsam Kamenar提到的问题与没有将for循环的内部封装在闭包中有关。

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

一个快速的解决方案是将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);
}

希望能有所帮助:)