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

101
Vistas
jQuery not return updated data-value
  1. click on first green button
  2. click check price button, return right? okay
  3. click second green button, then click again check price, return wrong! why?

$('button.setprice').click(function() {
  var txt = $(this).text();
  $('.price').text(txt).attr('data-price', txt);
});

$('.check').on('click',function(){
  alert($('.price').data('price'))
});
.setprice {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="price"></div>

<button class="setprice">1000</button>
<button class="setprice">2000</button>
<br/>
<button class="check">check price</button>

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

0

Apparently, you can't mix data() and attr() functions. It is well explained in this answer: https://stackoverflow.com/a/8708345/3785618

Since .data() does extra processing jQuery stores the results of attribute evaluation in $.cache - after all, once a data attribute has been evaluated it would be wasteful to re-evaluate on every .data() call - especially since data variables can contain complex JSON strings.

Although, this will work:

$('button.setprice').click(function() {
  var txt = $(this).text();
  $('.price').text(txt).data('price', txt);
});

$('.check').on('click',function(){
  alert($('.price').data('price'))
});
.setprice {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="price"></div>

<button class="setprice">1000</button>
<button class="setprice">2000</button>
<br/>
<button class="check">check price</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