0

I have this image element that sometimes is not loaded properly.

<img class="picture" src="pic/car.jpg" alt="car">

To solve this problem I found a solution using jQuery to prevent caching load image:

$(".picture").attr("src", "pic/car.jpg?"+d.getTime());

How to reload/refresh an element(image) in jQuery

That works fine. But how can I perform the same idea to reload a multiple image testimonials?

For example, each time a user changes his picture, I could apply the jQuery code to refresh the picture. But this code will not work when we have multiple images like this

<img class="picture" src="pic/car.jpg" alt="car">
<img class="picture" src="pic/car2.jpg" alt="car2">
<img class="picture" src="pic/car3.jpg" alt="car3">
<img class="picture" src="pic/car4.jpg" alt="car4">

$(".picture").attr("src", "pic/car.jpg?"+d.getTime());
$(".picture").attr("src", "pic/car2.jpg?"+d.getTime());
$(".picture").attr("src", "pic/car3.jpg?"+d.getTime());
$(".picture").attr("src", "pic/car4.jpg?"+d.getTime());

Of course I could use Id instead of class to grab each element. But I dont know previously how many pictures the user will upload.

Another solution is a loop over the database to find how many picture server will send and load jquery dynamically for each picture. But I dont think this is a good practice.

Any idea how to do that in another way?

Community
  • 1
  • 1
IgorAlves
  • 5,086
  • 10
  • 52
  • 83

2 Answers2

1

If i get your question right, you could do something like this:

$(".picture").each(function(){
   var currentSrc = $(this).attr("src");
   $(this).attr("src", currentSrc+"?"+d.getTime());
});
twain
  • 1,305
  • 11
  • 16
0

First of all when you use the jquery selector $(".picture") you are actually select ALL THE ELEMENTS with the class .picture. so in the first place you are assigning the attribute ("src", "pic/car.jpg?"+d.getTime()) to all elements with class .picture. Next you are doing the same with another name por the SRC/car2 and go on.

As twain says the better choice is use the each() method.