Javascript 使用MutationObserver时获取当前MutationRecord的新属性值?

Javascript 使用MutationObserver时获取当前MutationRecord的新属性值?,javascript,html,dom,mutation-observers,Javascript,Html,Dom,Mutation Observers,我有一些代码如下所示 const observer = new MutationObserver(records => { for (const record of records) { if (record.type !== 'attributes') continue handleAttrChange( record.attributeName!, record.oldValue,

我有一些代码如下所示

const observer = new MutationObserver(records => {
    for (const record of records) {
        if (record.type !== 'attributes') continue

        handleAttrChange(
            record.attributeName!,
            record.oldValue,
            record.target.attributes.getNamedItem(record.attributeName).value,
        )
    }
})
其中
handleAttrChange
参数是属性名称、旧值和新值

但是,正如您所知,第三个参数传递到了
handleAttrChange

record.target.attributes.getNamedItem(record.attributeName!)!。价值
始终是最新的属性值,而不是我们正在迭代的特定突变记录的“新值”(即,不是突变发生时观察到的“新值”)


我们如何获得每个突变发生时观察到的“新值”呢?

我认为使用
MutationObserver
是不可能的。a中的任何内容都不会公开新值,而且由于MuationObserver在微任务中运行,并且在发生更改后不会完全同步,因此可以从observer回调中的元素中检索的值可能在触发observer的更改后发生了更改,如您所见

const observer=new MutationObserver(记录=>{
for(记录的常量记录){
如果(record.type!=“attributes”)继续
log(div.dataset.foo);
控制台日志(记录);
}
});
observer.observe(div,{attributes:true});
div.setAttribute('data-foo','foo');
div.setAttribute('data-foo','bar')

我们可以这样模拟:

const observer=new MutationObserver(记录=>{
设LastAttributeValue={}
让name=''
for(记录的常量记录){
如果(record.type!=“attributes”)继续
name=record.attributeName
if(LastAttributeValue[名称]==未定义){
LastAttributeValue[名称]=记录.oldValue
持续
}
handleAttributeChange(名称,LastAttributeValue[name],record.oldValue)
LastAttributeValue[名称]=记录.oldValue
}
让attr
for(LastAttributeValue中的常量名称){
attr=el.attributes.getNamedItem(名称)
handleAttributeChange(名称,LastAttributeValue[name],attr==null?null:attr.value)
}
})

它所做的是,因为我们知道我们按顺序得到突变,并且在迭代过程中我们拥有给定属性的所有属性值,它只跟踪以前和当前属性值(每个属性名称),并使用每个以前和当前值触发
handleAttributeChange

谢谢提示!我提出并发布了一个解决方案。