2015-11-01 20 views
2

有沒有在javascript中檢測何時在javascript/jQuery中刪除某個HTML元素的方法? 在TinyMCE中,我插入一個滑塊,並且我想在所見即所得中刪除某些元素時刪除整個事物。JavaScript檢測何時刪除某個元素

回答

2

在大多數現代瀏覽器中,您可以使用MutationObserver來實現此目的。

你會做它的方式是這樣的:

var parent = document.getElementById('parent'); 
 
var son = document.getElementById('son'); 
 

 
console.log(parent); 
 
var observer = new MutationObserver(function(mutations) { 
 
    mutations.forEach(function(mutation) { 
 
    console.log(mutation); // check if your son is the one removed 
 
    }); 
 
}); 
 

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

 
observer.observe(parent, config); 
 

 
son.remove();

您可以查看正在運行的例子here

關於MutaitionObserver的更多信息here

+0

您發送給我的方式正確,我一直在尋找瀏覽器支持。 IE11支持MutationObserver。一個好的回退是addEventListener DOMNodeRemoved – poashoas

+0

請注意,它只適用於'兒子'是'父母'直接孩子。如果'son'是'父子',我們必須找到另一種方法來接近它 –

+1

@CliteTailor要觀察目標子孫(父子樹),請將子樹參數設置爲true。 –