2016-04-11 4 views
0

div要素の変更を検出したい。私はすでにいくつかの型(例:変更、ロード)で "addEventListener"を試してみました。ここで addEventListener - div要素の変更を検出しますか?

は私の例ですが、イベントがトリガされません。

<!doctype html> 
<html> 
    <head> 
    </head> 
    <body> 
     <div id='DivElement'>Test Div Text...</div> 
     <button type="button" onclick="EditDivElement()">click me!</button> 

     <script> 
      function EditDivElement() { 
       ClickCounter++; 
       SelectedDiv.textContent="new text content: " + ClickCounter; 
      } 

      function OnDivEdit() { 
       alert("success!"); 
      } 

      var ClickCounter = 0; 
      var SelectedDiv = document.querySelector("#DivElement"); 

      SelectedDiv.addEventListener("change", OnDivEdit); 
     </script> 
    </body> 
</html> 

(編集:それは、ブラウザアドオンのためだと、それは他のウェブサイト上で使用する必要があります)

+1

あなたはDOMの変更(突然変異)を聞いているので、あなたはすでに持っている機能にフックするだけです。 – adeneo

+0

ブラウザアドオン用で、他のウェブサイトで使用する必要があります。 – Flo93atx

+0

多分これ? http://stackoverflow.com/questions/15657686/jquery-event-detect-changes-to-the-html-text-of-a-div – Ronnie

答えて

1

あなたが使用することができますa MutationObserver。 MDNから

// select the target node 
var target = document.querySelector('#some-id'); 

// create an observer instance 
var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
    console.log(mutation.type); 
    });  
}); 

// configuration of the observer: 
var config = { attributes: true, childList: true, characterData: true }; 

// pass in the target node, as well as the observer options 
observer.observe(target, config); 

// later, you can stop observing 
observer.disconnect(); 

注:推奨されていません、私は私が書いた拡張でやっていること

DOMNodeInsertedに聞くことでした。

div.addEventListener("DOMNodeInserted", function (e) { 
    e.target // 
}, false); 
+0

ありがとうございました! MutationObserverはうまく動作しています。あなたの非難された機能も。 – Flo93atx