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

标签 javascript html observable

假设我希望 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/

相关文章:

ios - RxSwift - 如何按顺序链接可观察量

javascript - Google Maps Api V3 - 将多个监听器分配给同一标记对象

javascript - 使用 timeUpdate 和 currentTime

javascript - 将背景应用到 ionic 侧菜单

Angular 5 订阅和取消订阅 Observable

f# - 澄清 F# 中的事件、观察者和邮箱处理器

javascript - 如何在没有用户确认提示的情况下使用 javascript/extendscript 在 Illustrator 中打开一组 PDF 文件?

javascript - 何时使用 AngularJS 的数据绑定(bind)以及何时使用 Rails

javascript - 从预保存 Hook 中调用架构方法并更新属性

html - AMP : <amp-ad> not showing adense ads, 但字段为空