gpt4 book ai didi

javascript - jQuery 不返回新的数据属性

转载 作者:行者123 更新时间:2023-11-29 19:44:52 25 4
gpt4 key购买 nike

我正在尝试使用 data-attr 和 jQuery 完成一个非常简单的任务,检查这个例子:

标记:

<div data-name="Testing"></div>

JS

$(function(){
var div = $('div');
$(div).append($(div).data('name'));
$(div).attr('data-name', ' - Testing 2');
$(div).append($(div).data('name'));
console.log(div);
});

您可以在这里进行测试:http://jsfiddle.net/YsKJJ/16/

因此,它应该附加到 div 中正文Testing - Testing 2 , 但打印 TestingTesting .在控制台中,我检查了对象中的 attr 是否已更改,是的,具有新值 - Testing 2但是 jQuery 仍然返回原始值:(

有什么想法吗?

更新:

因此,根据 jQuery 文档,这种行为的原因是:

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

更多信息:jQuery Data vs Attr?

最佳答案

您正在更改属性,但这不会自动更新数据。这有效:

$(function(){
var div = $('div');
div.append(div.data('name'));
div.data('name', ' - Testing 2');
div.append(div.data('name'));
});

关于javascript - jQuery 不返回新的数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20435046/

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