Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery$(this).data()正在返回旧值_Javascript_Jquery - Fatal编程技术网

Javascript jQuery$(this).data()正在返回旧值

Javascript jQuery$(this).data()正在返回旧值,javascript,jquery,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=

我有以下代码:

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')
“#9900ff”

如您所见,实际元素的
数据颜色
#ffff00
。但是,jQuery的
.data()
方法返回
#9900ff
,该值是元素的
数据颜色的值,但是已经更改了(使用断点,我可以看到它已经更改了)。

jQuery只通过-读取数据属性,仅在第一次访问数据属性时才会对其进行检查(如果第一次访问是赋值,则不会进行检查)

在内部,jQuery it维护自己的“数据缓存”,否则它与数据属性没有任何关系。在第一次访问给定密钥时,通过DOM数据属性初始化该内部缓存

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


来自的相关部件如下所示

// 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 );

另见:


如果以前的数据发生了更改,您必须先删除以前的数据,然后才能再次访问它

$(this).removeData('color')

您是否尝试过使用
.attr('data-color')