我有以下代码:
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/