gpt4 book ai didi

javascript - 当 html 元素被实例化时通知

转载 作者:行者123 更新时间:2023-11-28 04:01:02 25 4
gpt4 key购买 nike

假设我希望 html 文件中出现特定的 div 元素。它为该 div“one”设置了 id。

我希望 javascript 在实例化该元素时通知我(例如 console.log),并且可能在渲染之前更改该 div 的 css(例如 width="100px")。如果碰巧该特定 div 不存在,则不执行任何操作或通知该 div 元素在页面完全加载时未呈现。

我听说 Observable 是在我预期发生某些事情时获取警报的方式,但是有人可以告诉我从哪里开始构建可以工作的代码吗?

编辑。这是为什么呢?我想在想要弹出的时候捕获广告,这样我就可以修改广告的 div。

最佳答案

如果我没猜错的话,您想观看 <div id="one" />元素。如果需要捕获不同的元素,请更新相应的条件和查询选择器。

var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
mutation.addedNodes.forEach(function (addedNode) {
if (!addedNode.getAttribute) {
return; // not an element node
}
if (addedNode.getAttribute('id') === 'one') { // replace with
// appropriate condition
// found, do whatever
}
var nodes = addedNode.querySelectorAll('div[id=one]'); // replace with
// appropriate selector
[].forEach.call(nodes, function (node) {
// found, do whatever
});
});
});
});

observer.observe(document.body, { // you might replace it with an appropriate
// more specific parent element
childList: true,
subtree: true
});

关于javascript - 当 html 元素被实例化时通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47117164/

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