简体   繁体   中英

jQuery image load, append to multiple div's

I am using the following code to preload an image:

$('<img src="'+ Image +'">').load(function() {
  $(this).appendTo('#background');
  $('#background').show();
});

This is working like it should. But, when I try to append the image to multiple div's, it only appends the image to the last div.

Any ideas?

I have tried this, but without result:

$(this).appendTo('#background, #second-div');

As referencing to your provided JS code. Assuming that you might have declared background as id . Try to declare it as a class and replace the below snippet. Hopefully, I guess it works.

$('<img src="'+ Image +'">').load(function() {
    $(this).appendTo('.background');
    $('.background').show();
});

If you pass a selector to .appendTo that matches more than one element, jQuery will clone your reference element - with all event listeners - and append the cloned element.

As your reference element is an image with an onload listener, the added element will also be an image with an onload listener, and you will be creating an infinite number of images.

The reason this appears to you as "not working" and not as flooding your browser with images, is likely because you are adding them to a hidden container, and you never reach the .show call.

One solution would be to use jQuery's one handler, which verifies that the load callback is fired exactly once:

Fiddle with infinite images

Fiddle with one image

The solution suggested in comments, with calling .clone() yourself before appending the image to a new - single - target, is also working, exactly because you're calling .clone() and not .clone(true) which is what .appendTo does internally, and which is what's causing the load listener to be preserved for the cloned object as well.

Fiddle with clone

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