简体   繁体   English

jQuery不返回新的数据属性

[英]jQuery doesn't returns the new data-attribute

I'm trying a very simple task working with data-attr and jQuery, check this example: 我正在尝试使用data-attr和jQuery进行非常简单的任务,请检查以下示例:

Markup : 标记

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

JS 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/ 您可以在这里进行测试: http : //jsfiddle.net/YsKJJ/16/

So, it should appends inside the div the text Testing - Testing 2 , but prints TestingTesting . 因此,应在div内附加文本Testing - Testing 2 ,但打印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 :( 在控制台中,我检查对象中的attr是否已更改,是的,具有新值- Testing 2但jQuery仍返回原始值:(

Any idea? 任何想法?

UPDATE: 更新:

So, the reason of this behavior according jQuery docs: 因此,根据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中)。

More information: jQuery Data vs Attr? 更多信息: jQuery Data vs Attr?

You are changing the attribute but this doesn't automatically update the data. 您正在更改属性,但这不会自动更新数据。 This works: 这有效:

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

Working demo http://jsfiddle.net/DDv8U/ 工作演示 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'));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM