Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wanna use jQuery's data() api to retrieve all the data attribute of an element. But the cache nature of this api is really annoying. Sometimes I need to change some data atribute of an element in javascript but the data() api always return the initial value of each data attribute. So I have to use the attr() to access each data attribute of an element to get its up-to-date value. Is there any way to overcome this cache thing and make data() always return the latest value every time I call it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

The short answer is: don't use jQuery .data() for dynamically set data attributes, unless you can guarantee that data attributes are always set by jQuery.

Either solution below will work:

  • Use vanilla JS .getAttribute() instead
  • Use jQuery .attr() instead

Here's the relevant part from the jQuery documentation (which I don't think really highlights how much this might surprise jQuery users):

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

Regarding why you might not use jQuery to set attributes: many client side templating languages build DOM, including data attributes.

Given the dynamically built HTML (as shown in DevTools:

<form data-test="300" ...

DOM API tells the truth:

 document.querySelector('form').getAttribute('data-test');

JQuery returns an out-of-date previous value (in this case, 19000):

 $('form').data('test');

jQuery attr returns the current value:

 $('form').attr('data-amount');

Vanilla JS getAttribute() returns the current value:

 document.querySelector('form').getAttribute('data-amount');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...