如何添加一个事件监听器,触发某个类型的元素被添加到DOM? [英] How can I add an event listener that triggers whan a certain type of element is added to the DOM?

查看:848
本文介绍了如何添加一个事件监听器,触发某个类型的元素被添加到DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当在当前窗口中创建新的iframe时,我想调用特定的方法。这是youtube iframe播放器我需要在当前窗口中创建或启用时监听新的iframe。有可能做那样的事吗?如果有任何办法,请告诉我。我已经尝试了以下代码,但此代码不会检测到动态创建的新iframe。我在谷歌尝试但没有得到任何信息

I want to call a specific method whenever a new iframe is created in the current window . It is youtube iframe player i need to listen to new iframes whenever it is created or enabled in current window . is it possible to do something like that ? Please let me know if there is any way .I have tried the below code but this code wont detect the new iframes which is dynamically created . I tried in google but didn't get any info

const iframes = document.getElementsByTagName('iframe');
  forEach(iframes, (iframe) => {
        addEventListeners(iframe);

      }
    }
  });


推荐答案

您可以使用 MutationObserver 。它可以让你听DOM的突变;它就像你在dom本身设置一个事件监听器,并在每次添加iFrame时监听:

You can use a MutationObserver. It lets you listen for mutations to the DOM; its like you are setting an event listener on the dom itself, and listening for whenever an iFrame is added to it:

(new MutationObserver(mutations => {
    mutations[0].addedNodes.forEach(node => {
        if (node.tagName.toLowerCase() === 'iframe') {
            //do stuff
        }
    });
})).observe(document.body, {childList: true});

这里我们正在收听 document.body ,我们只是监听其子节点的更改(添加或删除节点)。 forEach 遍历每个添加的节点(如果有)并检查它是否为 iFrame 。如果是,那么在do stuff行中做你需要做的事。

Here we are listening to document.body, and we are only listening for changes to its child nodes (a node is added or deleted). The forEach goes through each added node (if any) and checks if its an iFrame. If it is, then do what you need to do in the "do stuff" line.

这篇关于如何添加一个事件监听器,触发某个类型的元素被添加到DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆