2013-01-24 175 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