JQuery 数据选择器未使用 .data 更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9768165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:16:43  来源:igfitidea点击:

JQuery data selector not updating with .data

jqueryhtmljquery-selectors

提问by Adam Merrifield

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

基本上,如果我将一个 div 加载到具有data-test属性的页面上并使用 jquery 更改它的值,.data('test')我将无法再选择元素$('div[data-test="newValue"]')

var howMany = $('.t[data-test="test"]').length;
$('.result').html('start there are ' + howMany + ' divs with data "test"<br /><br />');
setTimeout(function() {
  $('#one, #three').data('test', 'changed');
}, 500);
setTimeout(function() {
  var test = $('.t[data-test="test"]').length,
    changed = $('.t[data-test="changed"]').length;
  $('.result').append('there are ' + test + ' divs still with data "test"<br /><br />there are ' + changed + ' divs still with data "changed"<br /><br />');
}, 1000);
setTimeout(function() {
  $('.t').each(function() {
    $('.result').append('div #' + $(this).attr('id') + ' has the test data of: ' + $(this).data('test') + '<br /><br />');
  });
}, 1500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="t" id="one" data-test="test">1</div>
<div class="t" id="two" data-test="test">2</div>
<div class="t" id="three" data-test="test">3</div>
<div class="t" id="four" data-test="test">4</div>
<div class="result"></div>

回答by Ben Lee

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:

jQuery .data() 最初使用data-属性中的值填充,但设置它仅将关联的新值存储在内存中。它不会更改 DOM 中的属性。要更改属性,您必须使用:

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

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

文档位于http://api.jquery.com/jQuery.data/

回答by Nicola Peluchetti

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()

那是因为我认为.data()在 jQuery中使用一个特殊的缓存对象来存储数据(实际上你甚至可以存储对象或复杂的数据),如果你检查所有的属性都没有改变。如果要更改属性,请使用attr()