Javascript'div empty'事件监听器

时间:2013-01-24 23:15:05

标签: javascript events listener

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

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

)};

1 个答案:

答案 0 :(得分: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);