Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda