6

すべての「いいね」ボタンの後に要素を追加したい(クロム拡張)。ページを更新せずにニュース フィードに投稿が追加されるため、イベント リスナー " 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(); 
    });

変更$("#contentArea")するdocumentと、すべてのページがクラッシュします。

4

2 に答える 2

7

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

});

or do what you need to perform every time a node is inserted in the DOM.


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);

Edit: As on jQuery 1.7, please use the '.on' function instead: http://api.jquery.com/on/


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 ...

I would suggest that you listen to the correct method and append your span there...

于 2012-05-19T18:46:08.690 に答える