Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
How can I append a date or time to an image and prevent it from caching using jQuery or JavaScript?

I created the following javascript code that appends a new date and time on click so that the browser does not pick up the image from the cache and loads it everytime. My code is:

$(#button).click(function(e) {
   e.preventDefault()
   $('.Myimage').attr('src',$('this').src + 'Testimage.png' + '?' + (new Date().getTime()));
});

This almost works fine but I'm getting an undefined message at the beginning of my image string.

<img src="undefinedTestimage.png?1628621212728" class="Myimage">

I'm not sure why. I figure that its some sort of typo. I'm also open to improving the code. Suggestions?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

$('this') is selecting a <this> element.

If you change it to $(this) it still won't be correct, because this is the button, not the image. Also, in jQuery you use .attr('src') to get the src attribute, not .src.

If you want to get the image's src, you need to loop over all the .Myimage elements. You can do that by giving a function argument to the .attr() method. This receives the old attribute as an argument, and returns the new value.

You don't need to concatenate Testimage.png, since that should already be in the src.

$('#button').click(function(e) {
  e.preventDefault();
  $('.Myimage').attr('src', (i, src) =>
    src + '?' + (new Date().getTime()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="foo.png" class="Myimage">
<img src="bar.png" class="Myimage">
<br>
<button id="button">Click</button>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda