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

标签 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,但已更改(使用断点,我可以看到它已经更改)。

最佳答案

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

另见:

关于javascript - jQuery $(this).data() 正在返回旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38733750/

相关文章:

jquery - 我想在输入复选框上添加一些 css

jQuery 从 iframe 代码获取 YouTube 视频 src

javascript - 单击 li 时的左动画

php - 滚动时固定对象路径

javascript - 加载时背景淡入

javascript - 图像 slider 标题

jQuery Datepicker UI 仅在单击关闭按钮或完成按钮时关闭

javascript - 猫头鹰旋转木马无法正常工作

javascript - 如何通过单击按钮将 d3.js 图的 csv 数据集切换到另一个 csv

javascript - 从匿名回调传回值的最简单方法?