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



基本上,如果我将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>

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

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

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

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

最新更新