简体   繁体   English

jQuery重新排列/交换img src导致照片重新加载时出现故障

[英]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. 我不确定最好的方法是什么,但是在页面上加载多个图像后,必须更改它们的src属性。 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: 我编写了一个jQuery函数,将它们像这样重新排列:

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. 从理论上讲,这种重新排列工作正常,但是当需要实际更改图像的src时,它会多次重新加载同一图像以及其他奇怪行为。

This is how I'm changing the src 这就是我更改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. 上面的行在第91行。

https://jsfiddle.net/4o17Ldxu/ 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"] . 完成此操作后,页面中将有两个<img>标记,它们与选择器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. 在随后的步骤中,如果尝试使用src="newimage.png"选择所有图像,最终将替换多个图像的src

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

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