简体   繁体   中英

jQuery doesn't returns the new data-attribute

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?

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/

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'));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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