JQuery data selector not updating with .data

2019-02-01 16:14发布

问题:

Basically if I have a div loaded onto a page with a data-test attribute and change the value of it with jquery's .data('test') I can no longer select the element with $('div[data-test="newValue"]')

See test here:

http://jsfiddle.net/VNaFs/1/

回答1:

jQuery .data() is initially populated with values from the data- attributes, but setting it only stores the associated new value in memory. It doesn't change the attribute in the DOM. To change the attribute, you have to use:

$('#one, #three').attr('data-test', 'changed');

The docs are at http://api.jquery.com/jQuery.data/



回答2:

That's because i think that .data() use a special cache object inside jQuery to store data (in fact you can evens store object or complex tipes of data), if you check all the attributes are unchanged. If you want to change the attribute, use attr()