How do I prevent a click handler being triggered when a child element is clicked?

前端 未结 3 1773
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 01:36

I have two div tags, first div is the father and the second div is son Inside the father like this

相关标签:
3条回答
  • 2020-12-07 02:03

    You can pass the event as one of the arguments in the closeFather function, then check whether the event target is the father element. See this example

    function closeFather(e) {
        if(e.target == document.getElementById('father')) {
            //do stuff
        }
    };
    

    Then in the HTML you just need to add the event argument to the javascript function.

    <div id="father" onclick="closeFather(event)">
    <div id="son"></div>
    </div>
    
    0 讨论(0)
  • 2020-12-07 02:08

    This is caused by a JavaScript trait called event bubbling. By default, your events will 'bubble up' into the DOM.

    When clicking a child node, you would automatically trigger a click event for it's parent node(s).

    By default, when clicking an element, bubbling happens from the inside out: this means that first the child element's click() event will be trigged, then it's parent, etc.

    You can solve the problem by adding a secondary click handler to your child element as well and telling the browser to stop bubbling in a cross-browser compatible way like so (see live example):

    <script language="javascript">
        function parentHandler(e) {
            alert('parent clicked');
        };
    
        function childHandler(e) {
            if (!e) var e = window.event;
            e.cancelBubble = true;
            if (e.stopPropagation) e.stopPropagation();    
    
            alert('child clicked');
    
        };    
    </script>
    
    <div id="parent" onclick="parentHandler(event);">
        Foo
        <div id="child" onclick="childHandler(event)">
            Bar
        </div>
    </div>
    
    0 讨论(0)
  • 2020-12-07 02:21

    It's event bubbling. Core part of DOM Events. You could return false and prevent bubbling in your handler (closeFather, but you should pass event to it) if event triggered by son.

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