基本上,如果我将一个 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');
关于JQuery 数据选择器未使用 .data 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9768165/