防止子元素点击触发父元素的点击事件

12

我有一个选择器,绑定了一个点击事件,用于移除弹出窗口。然而,我只希望选择器处理点击事件,而不希望选择器的子元素触发点击事件。

我的代码:

<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>

当点击 .popup-content 时,它会触发点击事件,而我不希望 #popup 的子元素也执行该事件。

jQuery 代码:

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

1
可能是Jquery点击事件传播的重复问题。 - Felix Kling
4个回答

17

在你的#popup事件处理程序中,检查e.target == this。例如:

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

这样做比绑定额外的点击处理程序到所有子元素要容易得多。


1
感谢提供另一种处理父元素点击事件,同时允许子元素拥有自己的事件处理程序的示例。这正是我需要检查的内容。我使用了if(!$(e.target).is('a'))而不是if(e.target == this),但这使我朝着正确的方向前进了。 - Lenny Sirivong
我还需要使用if(!$(e.target).is('a'))。我在“each”函数中使用它(也许使用循环可以确定解决方案)。 - Michal - wereda-net

14

尝试:

e.stopPropagation();
return false; 

在您的事件处理程序中


2
返回false与调用e.stopPropagation()e.preventDefault()是相同的。 - Felix Kling
啊,我之前不太了解stopPropagation的用法,谢谢! - MacMac
+1,谢谢你分享这个信息。我之前也不知道stopPropagation()的用法。 - Patrick Moore
当链接<a>是具有点击事件的元素的父元素时,e.stopPropagation无法工作。只有e.preventDefault和返回false才能起作用。谢谢! - QMaster

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

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

或者

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

在你的情况下 - 这是一样的,但有时候你如果不用 e.stopPropagation() 是做不到这样的事情的。例如:
$('.popup-content a').bind('click', function(e)
{
    e.stopPropagation();
    return confirm("Are you sure?");
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接