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

时间:2016-08-03 03:11:05

标签: javascript jquery

我有以下代码:

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

我在第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"

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

2 个答案:

答案 0 :(得分:28)

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

在内部,jQuery维护着自己的数据缓存&#39;否则与数据属性无关。在第一次访问给定密钥时,从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 );

另见:

答案 1 :(得分:0)

您必须先删除以前的数据,然后再进行更改(如果更改)

$(this).removeData('color')