Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Preventing Child from firing parent's click event

Consider the following snippet:

<div class="div-outer">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    <div class="div-inner" style="background:red">
        Curabitur hendrerit vehicula erat, ut gravida orci luctus vitae.
    </div>
</div>

Now suppose the outer div has a live click associated with it. How do I make sure that the live click is not triggered when I click anywhere in the inner div?

Edit:

Here's the JS as requested

$(".div-outer").live("click",function(){alert("hi")}); 

This should not be triggereed when clicking on ".inner-div"

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You have to add an event listener to the inner child and cancel the propagation of the event.

In plain JS something like

document.getElementById('inner').addEventListener('click',function (event){
   event.stopPropagation();
});

is sufficient. Note that jQuery provides the same facility:

$(".inner-div").click(function(event){
    event.stopPropagation();
});  

or

$(".inner-inner").on('click',function(event){
    event.stopPropagation();
});  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...