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

标签 jquery html jquery-selectors

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

关于JQuery 数据选择器未使用 .data 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9768165/

相关文章:

jquery-plugins - 调试 jQuery 插件以在两个相等的列中显示动态列表

html - 如何在动态 div 周围创建边框?

javascript - 带 JSON 的 JQuery 选择器

javascript - window.open 不适用于 _self

javascript - jQuery 1.9 复选框计数

javascript - 如何使用 jQuery 滚动到某个元素?

html - 如何使字体很棒以在实时网站上显示

javascript - "all not first in a div preceded by a object with class"的 jQuery 选择器

javascript - 我有一个有效的 json 但我不断收到 "syntaxerror json.parse unexpected end of data at line 1"!

javascript - 将在单击时删除特定单词的 jQuery 函数