插入时动态创建的 DOM 节点的处理程序 [英] Handler for dynamically created DOM nodes as they are inserted

查看:33
本文介绍了插入时动态创建的 DOM 节点的处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在我不拥有或控制的页面上运行自定义脚本.很多时候,这些页面都动态创建了我想对其应用函数的内容.

I enjoy running custom scripts on pages that I do not own or control. Many times these pages have dynamically created content that I would like to apply a function to.

这可能吗?如果是这样,我该怎么做?理想情况下,我正在寻找一些实时 jQuery 的 live 方法,除了绑定像 click 这样的事件,它更像是在 DOM 中加载元素时发生的事件.load 事件适用于某些元素,但我不认为所有...

Is this possible? If so, how can I do this? Ideally I am looking for something live jQuery's live method, except instead of binding an event like click it would be more like an event that happens when the element is loaded in the DOM. load event would work for some elements but I don't think for all...

对于这个问题,假设您无法查看或更改插入 DOM 节点的代码.我想要一种可以在用户脚本或书签中使用的技术,可以在多个不相关的网站上使用.

For this question, assume that you cannot look at or change the code that is inserting the DOM nodes. I would like a technique that I could use in a userscript or bookmarklet that could be used across multiple unrelated sites.

我正在寻找可以在我的反转颜色书签上使用的东西:JavaScript:反转页面所有元素的颜色

I am looking for something to use on my invert colors bookmarklet: JavaScript: Invert color on all elements of a page

推荐答案

假设您运行的是 Firefox 或 Chrome 等浏览器,您可以监听 DOMNodeInserted 事件:

Assuming you're running a browser like Firefox or Chrome, you could listen for the DOMNodeInserted event:

$(document).on('DOMNodeInserted', function(e) {
    $(e.target).css({ color : '#c00' });
});

$('body').append('<div>test</div>');​

小提琴:http://jsfiddle.net/VeF6g/(可能在 IE 中失败)

Fiddle: http://jsfiddle.net/VeF6g/ (probably fails in IE)

更新:该事件已弃用.您应该使用 MutationObserver:

Update: The event is deprecated. You should use a MutationObserver:

var observer = new MutationObserver(function(mutationList) {
    for (var mutation of mutationList) {
        for (var child of mutation.addedNodes) {
            child.style.color = '#c00';
        }
    }
});
observer.observe(document, {childList: true, subtree: true});

// ready? Then stop listening with
observer.disconnect();

更多信息在这里:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

这篇关于插入时动态创建的 DOM 节点的处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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