jQuery $(this).data()返回旧值

Mir*_*318 12 javascript jquery

我有以下代码:

updateColors = function() {
  $(".color-preview").each(function() {
    return $(this).css('background-color', $(this).data('color'));
  });
  return null;
};
Run Code Online (Sandbox Code Playgroud)

我在第3行放了一个断点,然后在控制台中键入以下内容:

> this
<div class=?"color-preview" data-observer=?"{"attr":?"data-color", "observe":?"btn_col"}?" data-color=?"#ffff00" style=?"background-color:? rgb(153, 0, 255)?;?">?</div>?

> $(this).data('color')
"#9900ff"
Run Code Online (Sandbox Code Playgroud)

如您所见,实际元素data-color#ffff00.但是,jQuery的.data()方法正在返回#9900ff,这元素的值data-color,但已被更改(并且使用断点,我可以看到它已经更改了).

use*_*740 31

jQuery只读取数据属性.data- 也就是说,数据属性只会在第一次访问时被检查(如果第一次访问是赋值,则永远不会检查).

在内部,jQuery它维护着自己的"数据缓存",否则它与数据属性无关.在给定密钥的第一次访问时,从DOM数据属性中引出此内部高速缓存.

如果目标是始终读取和/或改变DOM属性,请改用该.attr方法.


https://github.com/jquery/jquery/blob/master/src/data.js中的相关部分如下所示.

// Attempt read from the cache - if found, there is NO reading from DOM/data-*
// The key will always be camelCased in Data
data = dataUser.get( elem, key );
if ( data !== undefined ) {
   return data;
}

// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, key );

// ..

function dataAttr( elem, key, data ) {
    var name;

    // If nothing was found internally, try to fetch any
    // data from the HTML5 data-* attribute
    if ( data === undefined && elem.nodeType === 1 ) {
        // ..

        // Make sure we set the data so it isn't changed later
        // (NOTE: This operation adds the data to the cache
        //  and prevents reading any updated data-* attribute values.)
        dataUser.set( elem, key, data );
Run Code Online (Sandbox Code Playgroud)

也可以看看:


Adi*_*mar 5

如果更改了,您必须在再次访问之前删除这样的先前数据

$(this).removeData('color')
Run Code Online (Sandbox Code Playgroud)