Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

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

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

<div id="father"> 
<div id="son"> </div>
</div>

And I've added an event (onclick) in div father like this

<div id="father" onclick="closeFather()"> 
<div id="son"> </div>
</div>

My question is why the son inherits the father in the event.

I want when I click on the Father div implement the event, but when i click on the son does not implement anything because it does not have any event.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...