简体   繁体   中英

Prevent custom event from executing

I want to prevent custom event on parent when child is clicked. Note that I don't have access to the code of parent event. I've tried doing e.preventDefault() on the button itself but it doesn't help.

Is there any way of ignoring all parent events when something inside of it is clicked?

 $(function(){ // Note that this is just an example, I don't have access to this code // This is some custom event inside custom plugin $('.container').on('click', function() { alert('This should be alerted only if you click on green box'); }); $('.btn').on('click', function() { // Here I want to make sure that *parent* events are not triggered. alert('Button is triggered, green box should be not triggered'); }); }); 
 .container { width: 300px; height: 200px; background: green; padding-top: 100px; } .btn { width: 100px; height: 100px; display: block; margin: auto; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <button class="btn">Click Me</button> </div> 

Since you're using jQuery, you can use the event.stopPropagation() method. The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. You can see it in action here

   $(document).ready(function () {
       $("#button").click(function (event) {
           alert("This is the button.");
           // Comment the following to see the difference
           event.stopPropagation();
       });

       $("#outerdiv").click(function (event) {
           alert("This is the outer div.");
       });
   });

In this simple example, if you click on the button, the event is handled by its own handler and it won't bubble up the DOM hierarchy. You can add a very simple handler calling event.stopPropagation() on the button and it won't bubble up. No need to mess with the parent's JS.

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