“DOMNodeInserted”时添加一个元素事件叫 [英] Add an element when "DOMNodeInserted" event called
问题描述
我想在每个like按钮(chrome extension)之后添加一个元素。由于帖子被添加到新闻Feed而不刷新页面,我必须添加事件监听器 DOMNodeInserted
。但是,当我尝试将 after()
函数放在其中时,它不起作用。
I want to add an element after every "like" button (chrome extension). Since posts are added to the news feed without refreshing the page, I have to add an event listener "DOMNodeInserted
". But when I try to put the after()
function inside it, it doesn't work.
代码:
$("#contentArea").addEventListener("DOMNodeInserted", function(event) {
$(".like_link").after('<span class="dot"> · </span><button class="taheles_link stat_elem as_link" title="תגיד תכל´ס" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{"tn":">","type":22}"><span class="taheles_default_message">תכל´ס</span><span class="taheles_saving_message">לא תכלס</span></button>');
$(".taheles_saving_message").hide();
});
当我更改 $(#contentArea)
到文件
它会崩溃所有的页面。
When I change $("#contentArea")
to document
it crashes all the page.
推荐答案
想要在jQuery中添加一个事件监听器,这不是方法,corect的方式应该是:
if you want to add an event listener in jQuery, that is not the method, the corect way should always be:
$(document or window).bind( your_event_name, function(event) { your_callback });
记住这一点,你可以写:
with this in mind, you can write:
$(document).bind('DOMNodeInserted', function(event) {
alert('inserted ' + event.target.nodeName + // new node
' in ' + event.relatedNode.nodeName); // parent
});
或执行每次在DOM中插入节点时需要执行的操作。
or do what you need to perform every time a node is inserted in the DOM.
对于您的信息,如果要使用 addEventListener
,则需要使用plain javascript,而不是jQuery。
for your information, if you want to use addEventListener
you need to use plain javascript and not jQuery.
document.addEventListener("DOMNodeInserted", function () {
// your code
}, false);
编辑:对于jQuery 1.7,请使用'.on'功能: http://api.jquery.com/on/
As on jQuery 1.7, please use the '.on' function instead: http://api.jquery.com/on/
您的方法出现的另一个错误(如果有效)是您将打破您的应用程序,因为插入节点并调用 DOMNodeInserted
(因为您插入了一个节点),并将再次插入节点,并调用 DOMNodeInserted
再次...
another error that comes up of your method (if it worked) is that you will break your application as you are inserting a node and call the DOMNodeInserted
(cause you have inserted a node) and that will insert the node again, and call the DOMNodeInserted
again...
你可以看到发生了什么...
you can see what is going on ...
我建议你听正确的方法,并附加你的 span
那里...
I would suggest that you listen to the correct method and append your span
there...
这篇关于“DOMNodeInserted”时添加一个元素事件叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!