jQuery不返回新的数据属性 [英] jQuery doesn't returns the new data-attribute
问题描述
我正在尝试使用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
文本测试 - 测试2
,但打印 TestingTesting
。在控制台中,我检查了对象中是否更改了attr,是的,新值 - 测试2
但是jQuery仍然返回原始值:(
任何想法?
更新:
<那么,这个行为的原因是根据jQuery docs:
第一次数据属性是$时拉出数据属性b $ b被访问,然后不再被访问或变异(所有数据值
然后在内部存储在jQuery中)。
更多信息: jQuery Data vs Attr?
工作演示 http:// jsfiddle .net / DDv8U /
- API: http://api.jquery.com/data/ - 尝试使用此
$(div ).data('name',' - Testing 2');
休息应符合需要:)
代码
$(function(){
var div = $('div');
$(div).append($(div).data('name'));
$ (div).data('name',' - Testing 2');
$(div).append($(div).data('name'));
});
I'm trying a very simple task working with data-attr and jQuery, check this example:
Markup:
<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);
});
You can test it here: http://jsfiddle.net/YsKJJ/16/
So, it should appends inside the div
the text Testing - Testing 2
, but prints TestingTesting
. In console I checked if the attr was changed in the object, and yes, has the new value - Testing 2
but jQuery still returns the original value :(
Any idea?
UPDATE:
So, the reason of this behavior according jQuery docs:
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).
More information: jQuery Data vs Attr?
Working demo http://jsfiddle.net/DDv8U/
- API: http://api.jquery.com/data/ - try using this
$(div).data('name', ' - Testing 2');
rest should fit the need :)
code
$(function(){
var div = $('div');
$(div).append($(div).data('name'));
$(div).data('name', ' - Testing 2');
$(div).append($(div).data('name'));
});
这篇关于jQuery不返回新的数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!