有点好奇,因为我知道 HTMLCollections 会自动更新自己,所以我尝试使用 Proxy 观察它们。如下所示
let imagesCollection = document.images;
let io = new Proxy(imagesCollection, {
set: (target, prop, value, reciever) => {
// do stuff
// apply default behaviour
return Reflect.set(target, prop, value);
}
});
// test the block by adding new elements
document.body.insertAdjacentHTML("beforeend", "<img>");
document.body.insertAdjacentHTML("beforeend", "<img class='img'>");
document.body.insertAdjacentHTML(
"beforeend",
"<img class='img' src='https://picsum.photos/200/300'>"
);
但是当尝试动态添加一些图像时,没有任何 react ......所以我的问题是:
最佳答案
如果我理解正确,代理会拦截代理的操作,而不是目标:
let target = {};
let proxy = new Proxy(target, {
set: (target, prop, value, reciever) => {
console.log(prop, value);
return Reflect.set(target, prop, value);
}
});
target.foo = 'I am not intercepted.';
proxy.bar = 'I am intercepted.';
所以在你的情况下,操作
io
被拦截,同时操作 imagesCollection
或 document.images
不是。所以突变观察者是一个更好的选择。
关于javascript - 如何观察 HTMLCollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67948240/