【问题标题】:Javascript global "creation element" listener [duplicate]Javascript全局“创建元素”侦听器[重复]
【发布时间】:2017-07-01 19:23:29
【问题描述】:

如何在 Javascript 中添加全局侦听器,以便查看创建了哪个 html 元素(如 div、span 等),并在需要时对其进行装饰?

在我的情况下,如果满足某些条件,我想将类属性添加到 html“输入”元素。

这是一个交互式网站,所以元素是动态创建的,所以当作为输入元素加载的页面还没有创建时我不能这样做。

【问题讨论】:

  • 我看了看,玩过,但我不认为它是复制品。我想了解在 DOM 上某处“每次”创建 InputElement 的情况,而使用 MutationObserver 我必须指定要观察 DOM 突变的元素,它只会通知我指定的元素上的突变。但我不知道要指定哪个元素。如果我指定了 BODY,我只会看到添加/删除的几个元素,我不会被告知作为 BODY 的子项的子项创建的 INPUT 元素。还是我错过了什么?
  • 我找到了:是的,它是重复的。我将 MutationObserver 与子树选项一起使用。我使用了 childList 选项,但这还不够。现在,当在屏幕上的任何位置创建任何输入元素时,我都会收到通知。

标签: javascript html dom-events


【解决方案1】:

MutationObserver 为开发人员提供了一种对 DOM。它被设计为替代定义的突变事件 DOM3 事件规范。 ..for more details

示例:

// select the target node
var target = document.getElementById('some-id');

// create an observer instance
var observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();

【讨论】:

  • 'some-id' 应该是 上的 id 吗?以及如何为侦听器创建和接收的 元素添加属性?
猜你喜欢
  • 2011-01-28
  • 2013-03-30
  • 2021-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 2013-06-23
相关资源
最近更新 更多