简体   繁体   中英

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

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

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

note that the base_url is 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.

Because .load is an asynchronous event, callback passed to .load will only run when one of the images is loaded. 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.

One quick solution is to wrap the inner logic of your for loop in an explicitly bound immediately invoked function expression. 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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