MutationObserver 连续收到两条属性变更,为什么读到同一个当前值?
解释 MutationObserver 的 oldValue 与 target 当前属性读数为什么出现在同一批记录里,并演示如何在写入位置记录前后值。
MutationObserver 连续收到两条属性变更,为什么读到同一个当前值?
用 MutationObserver 观察节点的 data-stage,连续将其设为 loading 和 ready。回调明明收到了两条变更记录,从两条记录的 target 读取属性时,结果却都是 ready。中间的变更已经留下了记录,只是读取当前值时,两次写入都已经完成。
把旧值和当前值打印在同一行
先将属性设为 idle,再启动观察。配置 attributeFilter 只观察 data-stage,并启用 attributeOldValue,让每条记录保留对应那次写入前的属性值。节点可以留在文档之外,观察器直接观察它。
{
const node = document.createElement('div');
node.setAttribute('data-stage', 'idle');
const watcher = new MutationObserver((records) => {
for (const { oldValue, target, attributeName } of records) {
const current = target.getAttribute(attributeName);
console.log(JSON.stringify({ oldValue, current }));
}
watcher.disconnect();
});
watcher.observe(node, {
attributes: true,
attributeFilter: ['data-stage'],
attributeOldValue: true,
});
node.setAttribute('data-stage', 'loading');
node.setAttribute('data-stage', 'ready');
}

两条记录都指向同一个节点
第一次写入时,记录的 oldValue 是 idle。第二次写入时,新记录的 oldValue 是 loading。两次同步写入完成后,浏览器在微任务中把两条记录一起交给回调。两条记录的 target 指向同一个 DOM 节点,getAttribute() 每次都读这个节点当时的属性值,所以两次都是 ready。

根据场景决定取值时机
如果观察器只用于触发界面刷新,回调里读取一次 data-stage 就够了。如果日志要列出每次状态变化,而且写入路径由自己的代码控制,可以统一通过 setStage() 修改属性,在写入前后分别取值。
{
function setStage(node, next) {
const before = node.getAttribute('data-stage');
node.setAttribute('data-stage', next);
const after = node.getAttribute('data-stage');
return { before, after };
}
const node = document.createElement('div');
node.setAttribute('data-stage', 'idle');
for (const next of ['loading', 'ready']) {
console.log(JSON.stringify(setStage(node, next)));
}
}

这两次调用分别留下 idle → loading 和 loading → ready,日志只覆盖经过 setStage() 的写入。对第三方脚本直接修改属性的情况,仍可用观察器发现变化。解读每条记录时,oldValue 对应这次修改发生前的值,getAttribute() 对应读取那一刻的值。
IndexedDB 倒序去重时,为什么 prevunique 取到较小的主键?
2026-12-02
JS怎么获取当前选中的单选框值
2026-12-02
重复调用 addEventListener,能把监听改成 once 吗?
2026-12-02
