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>

4
  • 2
    Try with $('.price').attr('data-price') Commented Oct 18, 2021 at 13:42
  • 1
    Does this answer your question? jQuery .data() does not work, but .attr() does Commented Oct 18, 2021 at 13:46
  • 2
    attr() reads from the DOM, data() reads from a cache in memory which jQuery holds. You need to use the same method as getter and setter. You cannot mix and match. Commented Oct 18, 2021 at 13:47
  • Thanks everyone, now I understand what was my problem, regard Commented Oct 18, 2021 at 13:48

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.