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>