gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:26:43 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com