Prevent click from child firing parent click event

情到浓时终转凉″ 提交于 2019-12-17 18:38:54

问题


I have a selector that binds a click event which will remove the popup. However, I only want the selector to handle the click, instead of the children of the selector to be able to fire the click event.

My code:

<div id="popup">
  <div class="popup-content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</div>

When clicking on .popup-content, it will fire the click event when I don't want the children of #popup to do so.

The jQuery Code:

$('#popup').bind('click', function()
{
    $(this).remove();
});

回答1:


try:

e.stopPropagation();
return false; 

in your event handler




回答2:


In your event handler for #popup check if e.target == this. i.e.:

$('#popup').bind('click', function(e) {
    if(e.target == this) $(this).remove();
});

Doing this is much easier than binding extra click handlers to all the children.




回答3:


$('.popup-content').bind('click', function(e)
{
    e.stopPropagation();
});

or

$('.popup-content').bind('click', function(e)
{
    return false;
});

In your case - it's same, but sometimes you can't do such thing without e.stopPropagation(). For example:

$('.popup-content a').bind('click', function(e)
{
    e.stopPropagation();
    return confirm("Are you sure?");
});



回答4:


{if(e.target == this ){ return;}});


来源:https://stackoverflow.com/questions/6929198/prevent-click-from-child-firing-parent-click-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!