How to cancel click event of container div trigger when click elements which inside container in JQuery?

后端 未结 3 1885
终归单人心
终归单人心 2021-01-12 02:32

E.g

I am not fire when click me
$(\'.container\').click(function(){
相关标签:
3条回答
  • 2021-01-12 02:50

    As a more general solution, you should check e.target in container's click event handler.

    $('.container').click(function(e) {
       // If you want to ignore clicks to anything inside the `.container` div:
       if (!$(e.target).hasClass('container')) return;
       // or, if you only want the `.inside` div to not fire the event,
       if ($(e.target).hasClass('inside')) return;
    
       // container do something here
    });
    

    This way you're not preventing propagation of the event, which would break bound live handlers.

    0 讨论(0)
  • 2021-01-12 02:54

    Add a click event handler to inside as follows:

    $('.inside').click(function(event) {
        // do anything you might want with the click for inside
        return false; // prevents click event from bubbling up the DOM hierarchy
    });
    

    Alternatively, event.stopPropagation() also prevents bubbling like so:

    $('.inside').click(function(event) {
        // do anything you might want with the click for inside
        event.stopPropagation(); // prevents click event from bubbling up the DOM hierarchy
    });
    

    This article explains event bubbling.

    0 讨论(0)
  • 2021-01-12 03:08
    $('.inside').click(function(e) {
        e.stopPropagation();
    });
    

    That should work for you. It stops any click in the inside div from bubbling up to the container.

    Here's a quick example as well - http://jsfiddle.net/Yf8Ra/1/

    0 讨论(0)
提交回复
热议问题