简体   繁体   中英

jQuery rearrange/swap img src causes glitched reloading of photos

I'm not sure what the best method for this would be, but I have to change the src attribute for several images on a page after they've loaded. I need to rearrange them so to speak.

In their original format, they are displayed like this:

1    5    9
2    6    10
3    7    11
4    8    12

I have written a jQuery function that rearranges them like this:

1    2    3
4    5    6
7    8    9
10   11   12

The rearranging works fine in theory, but when it comes time to actually change the src of the image it reloads the same image more than once and other strange behavior.

This is how I'm changing the src

$('img[src="image.png"]').attr('src', 'newimage.png');

Here is a fiddle containing the function I use to rearrange. The line above is on line 91.

https://jsfiddle.net/4o17Ldxu/

In the fiddle, click "generate swap list" and look in your browser console, you'll see that it tells you which images should be swapped where, everything there is perfect, but when you click the button again and click "now rearrange" it causes all the glitches.

Is there anyway to prevent this? Or is there a better way to go about swapping/rearranging images in this manner?

I think the problem is that you are not actually "swapping" images - you're setting a first image equal to a second, and leaving the second unchanged. For example, your code logs:

Swap Photo 4 with Photo 2

But what it is actually doing is:

$('img[src="image.png"]').attr('src', 'newimage.png');

After this operation completes, you will have two <img> tags in your page that will match the selector img[src="newimage.png"] . In subsequent steps, if you try and select all images with src="newimage.png" , you'll end up replacing the src of multiple images.

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