jQuery不返回新的数据属性 [英] jQuery doesn't returns the new data-attribute

查看:97
本文介绍了jQuery不返回新的数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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





休息应符合需要:)



代码

  $(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/

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆