简体   繁体   English

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

[英]jquery.load() inside a for loop not working

I am trying to use the ,load function of jquery inside a for loop to load images on to my product catalogue where the url of the image is returned by a php script 我正在尝试在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);
        }
    });
}

The php file returns changes the header location to the url of the image ie in this case php文件返回将标题位置更改为图像的url,在这种情况下

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

note that the base_url is http://localhost/plum_final/ 请注意,base_url是http:// localhost / plum_final /

While loading directly using the The images load just fine 在直接使用加载时,图像加载正常

The problem as @Stephen Sarcsam Kamenar mentioned has to do with not wrapping the inner part of the for loop in a closure. @Stephen Sarcsam Kamenar提到的问题与未将for循环的内部包装在闭合中有关。

Because .load is an asynchronous event, callback passed to .load will only run when one of the images is loaded. 由于.load是一个异步事件,因此传递给.load的回调仅在加载其中一个图像时运行。 Because it's closing over access to the image variable, whatever the most recent value of the image variable is will be used as the argument to append. 因为它结束了对image变量的访问,所以无论image变量的最新值是什么,都将用作添加的参数。

One quick solution is to wrap the inner logic of your for loop in an explicitly bound immediately invoked function expression. 一种快速的解决方案是将for循环的内部逻辑包装在显式绑定的立即调用的函数表达式中。 Like this: 像这样:

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

Hope that helps :) 希望有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM