简体   繁体   English

div删除并动态添加后如何触发事件?

[英]How to fire a event when a div got removed and added dynamically?

I have following type of code 我有以下类型的代码

<div id="parent-div">
  <div id="child-div">
    <!--content goes here -->
  </div>
</div>

The child div comes from third party service it will get attached or removed dynamically. 子div来自第三方服务,它将被动态附加或删除。 How to fire a javascript event during attaching the are removing the div 如何在附加期间触发javascript事件以删除div

You have 2 options: 您有2个选择:

  1. Have a loop - Every x milliseconds, check to see if child-div exists / does not exists 循环-每隔x毫秒,检查child-div存在/不存在
  2. Use the DOM4 MutationObserver - More info on this here . 使用DOM4 MutationObserver -这个更多信息在这里 Note: This is only currently supported in Google Chrome browser support 注意: Google Chrome 浏览器支持 目前仅支持此功能

Related question with answer about the DOM4 MutationObserver: 有关DOM4 MutationObserver的答案的相关问题:

https://stackoverflow.com/a/11141879/5620297 https://stackoverflow.com/a/11141879/5620297

if you are using jquery use .trigger() , 如果您使用的是jquery,请使用.trigger()

in the function or code you attach the child div, after attaching the child div put 在函数或代码中,在附加子div放置后附加子div

$("div#parent-div").trigger("child_div_attached");

in the function or code you remove the child div, after removing the child div put 在函数或代码中,在删除子div后删除子div

$("div#parent-div").trigger("child_div_removed");

then you can add event listener to parent div like, 那么您可以将事件侦听器添加到父div,例如,

$("div#parent-div").on("child_div_attached", function() {
  //what to do after child div attached
});

$("div#parent-div").on("child_div_removed", function() {
  //what to do after child div removed
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM