gpt4 book ai didi

javascript - 如何测试 MutationObserver

转载 作者:行者123 更新时间:2023-12-01 03:21:12 28 4
gpt4 key购买 nike

我想同步一些DOM节点属性。如果更改某个属性,则会更改其他元素属性。

我可以更改它,但我无法为其编写测试。该测试更改观察到的元素的属性,然后检查更改是否应用于其他元素。更改同步最终会发生,但不会在观察到的元素属性更改后立即发生。

this example我创建了三个 div,并希望将 #div1 的类属性同步到其他两个。

html:

<div id="div1" class="foo"></div>
<div id="div2" class="foo"></div>
<div id="div3" class="foo"></div>

js:

let div1 = document.getElementById("div1")
let div2 = document.getElementById("div2")
let div3 = document.getElementById("div3")

var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.target.getAttribute("class"))
//sync the new attribute value to
div2.setAttribute("class", mutation.target.getAttribute("class"))
div3.setAttribute("class", mutation.target.getAttribute("class"))
})
})
// pass in the target node, as well as the observer options
observer.observe(div1, { attributes: true, attributeFilter: ["class"]})

//the test sets the class attribute of div1 to 'bar'
div1.setAttribute("class", "bar")
//then checks if div2 and div3 class is set to 'bar'
console.log("is div2.class = 'bar'?", div2.getAttribute("class") == "bar")
console.log("is div3.class = 'bar'?", div3.getAttribute("class") == "bar")

输出是:

is div2.class = 'bar'? false
is div3.class = 'bar'? false
bar

MutationObserver 仅在检查后运行,然后将 div2.classdiv3.class 设置为 'bar'。所以我的问题是,如何使用 MutationObserver 测试属性的同步。

最佳答案

在检查更新的类之前,您需要等待突变观察者处理突变事件。

常见的技巧是使用setTimeout。请参阅this question了解它是如何工作的。

let div1 = document.getElementById("div1");
let div2 = document.getElementById("div2");
let div3 = document.getElementById("div3");

var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.target.getAttribute("class"));
div2.setAttribute("class", mutation.target.getAttribute("class"));
div3.setAttribute("class", mutation.target.getAttribute("class"));
});
});
// pass in the target node, as well as the observer options
observer.observe(div1, {
attributes: true,
attributeFilter: ["class"]
});

function testMutationObserver(mutation, afterMutation) {
//Perform the mutation, e.g. by setting a new class
mutation();

//setTimeout gives the MutationObserver a chance to see the changes
setTimeout(afterMutation);
}

testMutationObserver(
function() {
div1.setAttribute("class", "bar");
},
function() {
console.log("is div2.class = 'bar'?", div2.getAttribute("class") == "bar");
console.log("is div3.class = 'bar'?", div3.getAttribute("class") == "bar");
}
);
<div id="div1" class="foo"></div>
<div id="div2" class="foo"></div>
<div id="div3" class="foo"></div>

关于javascript - 如何测试 MutationObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45189537/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com