我正在尝试使用 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/