2016-04-11 68 views
0

我想檢測div元素的變化。我已經嘗試了一些類型的「addEventListener」(例如:change,load)。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

您可以使用一個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