简体   繁体   中英

.appendTo doesn't work in .bind(load) - jQuery

I have an issue by adding images to a div with .appendTo while I'm in a for-loop and in the .bind("load")-handler. I tried so many things but nothing worked, it only shows the last picture and not the three. The code is pretty simple as shown below.

If anyone has a hint for me, this would be great. Thanks in Advance!

 var $images = ["https://static.pexels.com/photos/769986/pexels-photo-769986.jpeg", "https://static.pexels.com/photos/767907/pexels-photo-767907.jpeg", "https://static.pexels.com/photos/746759/pexels-photo-746759.png"]; var i, figure, img; for (i = 0; i < $images.length; i += 1) { figure = $('<figure />'); img = $('<img />'); img.attr("src", $images[i]); img.unbind("load"); img.bind("load", function() { a = $('<a>', { href: this.src, itemprop: "contentUrl", 'data-size': this.width + "x" + this.height }); img.appendTo(a); a.appendTo(figure); figure.appendTo('#gallery-panel'); }); } 
 img { width: 10em; float: left; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <body> <div id="gallery-panel"></div> </body> </html> 

Change:

img.appendTo(a);

to:

$(this).appendTo(a);

You're running into the Javascript infamous Loop issue? because all the closures are using the same img variable.

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