检测javascript中删除的DOM项目

时间:2016-10-12 03:04:44

标签: javascript jquery

我正在编写一个带有id的插件。它为该id添加了一些代码并启动了一些事件。我发现的问题是,如果容器稍后被覆盖,我找不到关闭事件的方法,因此它们不会继续运行。下面是一个演示脚本,以显示我尝试过的内容。我无论如何都无法找到test2不存在并清除间隔。

$(function() {
				
  /* *********************************
  *  Simple example of something that could be done
  *  being told to work on id test2
  ********************************* */
				
  var a=0;
  $("#test2").append('<br>I Ran');
  var id=setInterval(function() {
    console.log("running");		//ctrl+shift+j will see message every second
  },1000);
					
  //try to remove id test2 is removed
  $(document).on("DOMNodeRemoved", function (e) {
    console.log(e.target.id,e.target);
    if (e.target.id=="test2") { //is never true since test2 was added by jquery
		clearInterval(id);	//stops message from being writen
    }
  })
					
					
  /* *********************************
  *  Some other part of app that wipes away the above script is playing with
  ********************************* */
					
$(document).on('click','#del',function(){
  $("#test").html('wipe out');	//replaces content of div test with test2.html 			
  });
				
});
			
<!DOCTYPE html>
<html lang="en">
  <header> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  </header>
  <body>
  <div id="test">
  <div id="2" class="test">
    <div id="test2">help</div>
  </div>
  </div>
  <div id="del">Press here to remove</div>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

问题是您正在删除test2的父级,因此目标永远不会成为您正在测试的对象。要解决这个问题,请在条件尝试中使用:

if ($(e.target).find("#test2").length) {
    clearInterval(id);
}

$(function() {
				
  /* *********************************
  *  Simple example of something that could be done
  *  being told to work on id test2
  ********************************* */
				
  var a=0;
  $("#test2").append('<br>I Ran');
  var id=setInterval(function() {
    console.log("running");		//ctrl+shift+j will see message every second
  },1000);
					
  //try to remove id test2 is removed
  $(document).on("DOMNodeRemoved", function (e) {
    console.log(e.target.id,e.target);
    if ($(e.target).find("#test2").length) {
		clearInterval(id);
    }
  })
					
					
  /* *********************************
  *  Some other part of app that wipes away the above script is playing with
  ********************************* */
					
$(document).on('click','#del',function(){
  $("#test").html('wipe out');	//replaces content of div test with test2.html 			
  });
				
});
			
<!DOCTYPE html>
<html lang="en">
  <header> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  </header>
  <body>
  <div id="test">
  <div id="2" class="test">
    <div id="test2">help</div>
  </div>
  </div>
  <div id="del">Press here to remove</div>
  </body>
</html>

答案 1 :(得分:0)

我无法相信没有人告诉过您:您正在使用已弃用的变异事件,如here中所述。

根据该页面的建议,您应该使用 Mutation Observer

以下是基于original example

使用Mutation Observer重新编写js代码的片段

&#13;
&#13;
$(function () {
    var a = 0;
    $("#test2").append('<br>I Ran');
    var id = setInterval(function () {
        console.log("running");
    }, 1000);
    // select the target node
    var target = document.getElementById("test");
    // create an observer instance
    var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            if (mutation.removedNodes.length > 0) { // You need to check if the mutation.removedNodes array contains div#test2 here. I'm just too lazy.
                clearInterval(id);	//stops message from being writen
                console.log("stopped!");
                console.log("You can set debugger here to play with mutation.removedNodes array!");
                observer.disconnect(); // stop observing
            }
        });
    });
    // configuration of the observer:
    var config = { childList: true };
    observer.observe(target, config); // start observe
    $(document).on('click', '#del', function () {
        $("#test").html('wipe out');	//replaces content of div test with test2.html 			
    });
});
&#13;
<!DOCTYPE html>
<html lang="en">
<header>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="site.js"></script>
</header>

<body>
  <div id="test">
    <div id="2" class="test">
      <div id="test2">help</div>
    </div>
  </div>
  <div id="del">Press here to remove</div>
</body>

</html>
&#13;
&#13;
&#13;