简体   繁体   中英

How can I prevent parent element event execution from code inside children event

My question in the title probably looks vague. And I sketched an example for the question:

 container.onclick = () => { alert(0); }; content.onclick = () => { alert("how can I prevent here appearance alert(0) from parent element event?"); //how can I prevent parent event by content clicked? };
 #container{ height: 100px; background-color: gray; } #content{ height: 50px; width: 150px; background-color: green; }
 <div id="container"> <div id="content"></div> </div>k

This is a simple example. In a real project, I can't combine these two events into one, because the first one is programmatically assigned somewhere in the bowels of my framework and it shouldn't be removed from the EventListener after clicking on content

In General, is it possible to somehow interrupt the execution of the call chain event by clicking in the DOM layers? I tried to do this:

content.onclick = () => {
  alert("how  can I prevent here appearance alert(0) from parent element event?");
  e.preventDefault();
  return false;
  //how can I prevent parent event by content clicked?
};

But this, of course, was not successful

For this, you can use stop propogation of js like this

<div id="container">
 <div id="content" onclick="event.stopPropagation();">
 </div>  
</div>

So when you click on content it will not trigger container event only.

You should pass the event by dependency injection to the specific method ( content.onclick ) and then stop the propagation of it.

 container.onclick = () => { alert(0); }; content.onclick = (e) => { e.stopPropagation(); alert("Voilà, this prevent that appears alert(0) from parent element event."); };
 #container{ height: 100px; background-color: gray; } #content{ height: 50px; width: 150px; background-color: green; }
 <div id="container"> <div id="content"></div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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