元素添加到页面时的事件 [英] Event when element added to page

查看:95
本文介绍了元素添加到页面时的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前在此讨论过:使用Jquery将元素添加到页面时如何执行操作?

响应者建议触发自定义事件一个div被添加到页面。但是,我正在撰写Chrome扩展程序,无法访问页面源。我在这里有什么选择?我想在理论上我可以使用 setTimeout 来不断搜索元素的存在,并添加我的动作,如果元素在那里。

The responder suggested triggering a custom event whenever a div was added to the page. However, I'm writing a Chrome extension and don't have access to the page source. What are my options here? I guess in theory I could just use setTimeout to continually search for the element's presence and add my action if the element is there.

推荐答案

由于DOM突变事件现在是已弃用(请参阅底部的注释)并附上最新的规范,您无法控制插入的元素,因为它们由其他人的代码添加,您唯一的选择就是持续检查它们。 p>

Since DOM Mutation Events are now deprecated (see note at the bottom) with the latest specifications, and you have no control over the inserted elements because they are added by someone else's code, your only option is to continuously check for them.

function checkDOMChange()
{
    // check for any new element being inserted here,
    // or a particular node being modified

    // call the function again after 100 milliseconds
    setTimeout( checkDOMChange, 100 );
}

一旦调用此函数,它将每xxx毫秒运行一次。我选择100,这是10次。

Once this function is called, it will run every xxx milliseconds. I choose 100, which is 10 times a second. Unless you need real time elements catch, it should be enough.

修改

根据本·戴维斯的评论,DOM 4级规范引入了突变观察者(另请参阅 Mozilla文档),其中替换不推荐的突变事件。

As commented by Ben Davis, DOM Level 4 specification introduces Mutation observers (also on Mozilla docs), which replace the deprecated mutation events.

这篇关于元素添加到页面时的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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