调用"DOMNodeInserted"事件时添加元素

Nad*_* S. 5 javascript jquery dom facebook

我想在每个"喜欢"按钮(chrome扩展名)之后添加一个元素.由于帖子被添加到新闻Feed而不刷新页面,我必须添加一个事件监听器" DOMNodeInserted".但是当我尝试将after()函数放入其中时,它不起作用.

码:

    $("#contentArea").addEventListener("DOMNodeInserted", function(event) {
        $(".like_link").after('<span class="dot"> · </span><button class="taheles_link stat_elem as_link" title="???? ???&acute;?" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{&quot;tn&quot;:&quot;&gt;&quot;,&quot;type&quot;:22}"><span class="taheles_default_message">???&acute;?</span><span class="taheles_saving_message">?? ????</span></button>');
        $(".taheles_saving_message").hide(); 
    });
Run Code Online (Sandbox Code Playgroud)

当我改变$("#contentArea")document崩溃的所有页面.

bal*_*dre 7

如果你想在jQuery中添加一个事件监听器,那不是方法,核心方式应该始终是:

$(document or window).bind( your_event_name, function(event) { your_callback });
Run Code Online (Sandbox Code Playgroud)

考虑到这一点,你可以写:

$(document).bind('DOMNodeInserted', function(event) {

    alert('inserted ' + event.target.nodeName + // new node
          ' in ' + event.relatedNode.nodeName); // parent

});
Run Code Online (Sandbox Code Playgroud)

或者每次在DOM中插入节点时执行您需要执行的操作.


为了您的信息,如果您想使用,addEventListener您需要使用普通的javascript而不是jQuery.

document.addEventListener("DOMNodeInserted", function () {
    // your code
}, false);
Run Code Online (Sandbox Code Playgroud)

编辑:与jQuery 1.7一样,请使用'.on'功能:http://api.jquery.com/on/


您的方法出现的另一个错误(如果它有效)是您在插入节点时调用应用程序并调用DOMNodeInserted(因为您已插入节点)并且将再次插入节点,然后DOMNodeInserted再次调用它. ..

你可以看到发生了什么......

我建议你听正确的方法,然后把你的方法附加span到......