0
  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>
Jack The Baker
  • 1,781
  • 1
  • 20
  • 51

1 Answers1

1

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>
Maksim I. Kuzmin
  • 1,170
  • 7
  • 16