Child element click event trigger the parent click event

前端 未结 5 1454
轮回少年
轮回少年 2020-11-28 09:24

Say you have some code like this:





   
相关标签:
5条回答
  • 2020-11-28 09:34

    You need to use event.stopPropagation()

    Live Demo

    $('#childDiv').click(function(event){
        event.stopPropagation();
        alert(event.target.id);
    });​
    

    event.stopPropagation()

    Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

    0 讨论(0)
  • 2020-11-28 09:36

    Without jQuery : DEMO

     <div id="parentDiv" onclick="alert('parentDiv');">
       <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
         AAA
       </div>   
    </div>
    
    0 讨论(0)
  • 2020-11-28 09:39

    Click event Bubbles, now what is meant by bubbling, a good point to starts is here. you can use event.stopPropagation(), if you don't want that event should propagate further.

    Also a good link to refer on MDN

    0 讨论(0)
  • 2020-11-28 09:48

    I faced the same problem and solve it by this method. html :

    <div id="parentDiv">
       <div id="childDiv">
         AAA
       </div>
        BBBB
    </div>
    

    JS:

    $(document).ready(function(){
     $("#parentDiv").click(function(e){
       if(e.target.id=="childDiv"){
         childEvent();
       } else {
         parentEvent();
       }
     });
    });
    
    function childEvent(){
        alert("child event");
    }
    
    function parentEvent(){
        alert("paren event");
    }
    
    0 讨论(0)
  • 2020-11-28 09:52

    The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

    You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object).

    Syntax:

    Here is the simple syntax to use this method:

    event.stopPropagation() 
    

    Example:

    $("div").click(function(event) {
        alert("This is : " + $(this).prop('id'));
    
        // Comment the following to see the difference
        event.stopPropagation();
    });​
    
    0 讨论(0)
提交回复
热议问题