0

有没有办法让 div 元素为空时监听?

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

)};
4

1 回答 1

2

您应该在事件处理程序中运行 David 的代码,例如DOMNodeInsertedDOMCharacterDataModifiedDOMSubtreeModified。后者是最推荐的。例如:

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

   }
)};

编辑:但是,如评论中所述,不推荐使用此类实现。正如 david 所建议的,另一种实现如下:

// 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);
于 2013-01-24T23:19:40.117 回答