2013-01-24 235 views
0

有沒有一種方法可以在div元素爲空時擁有監聽器?Javascript'div empty'事件監聽器

$('#myDiv').emptyEvent(function(){ 

)}; 
+0

可能重複[?是否有一個jQuery DOM變化監聽器(http://stackoverflow.com/questions/2844565/is-there-a -jquery-dom-change-listener) –

回答

2

您應該運行大衛的事件處理程序中的代碼,如DOMNodeInsertedDOMCharacterDataModified,或DOMSubtreeModified。後者是最值得推薦的。例如:

$('#myDiv').bind("DOMSubtreeModified", function(){ 
    if ($('#myDiv').html() == "") { 

    } 
)}; 

編輯:但是這種實現是棄用,如在註釋中規定。另一種實現,由大衛的建議,如下:

// select the target node 
var target = $("#myDiv")[0]; 

// create an observer instance 
var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
     if($("#myDiv").html() == ""){ 
     // Do something. 
     } 
    });  
}); 

// 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); 
+2

請注意,這些突變事件已被棄用,並已被突變觀察者所取代:https://developer.mozilla.org/en-US/docs/DOM/MutationObserver – david

+3

And sad事情是[棄用](http://stackoverflow.com/questions/6659662/why-is-the-domsubtreemodified-event-deprecated-in-dom-level-3) – epascarello

+0

的確他們是我正要評論那 – kidwon