jQuery's data() attribute does not update when element data changes

你说的曾经没有我的故事 提交于 2019-11-29 05:55:49

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 DOM 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 also return the current value:

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

You can also use jQuery's .removeData() method after updating the data attribute to reset its cache.

For example:

> document.querySelector('.sub-panels')
<div class=​"sub-panels">​…​</div>​

> document.querySelector('.sub-panels').setAttribute('data-test', 300);
undefined

> document.querySelector('.sub-panels')
<div class=​"sub-panels" data-test="300">​…​</div>​

> $('.sub-panels').data('test')
300

> document.querySelector('.sub-panels').setAttribute('data-test', 400);
undefined

> $('.sub-panels').data('test')
300

> $('.sub-panels').removeData();
[div.sub-panels, prevObject: jQuery.fn.init(1), context: document, selector: ".sub-panels"]

> $('.sub-panels').data('test')
400
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!