阻止点击儿童解雇父点击事件

Mac*_*Mac 12 jquery click

我有一个选择器绑定一个将删除弹出窗口的单击事件.但是,我只希望选择器处理单击,而不是选择器的子节点才能触发单击事件.

我的代码:

<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>
Run Code Online (Sandbox Code Playgroud)

单击时.popup-content,如果我不想让孩子这样做,它将触发click事件#popup.

jQuery代码:

$('#popup').bind('click', function()
{
    $(this).remove();
});
Run Code Online (Sandbox Code Playgroud)

Ari*_*iel 17

在您的事件处理程序中#popup检查是否e.target == this.即:

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

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


Ada*_*dam 14

尝试:

e.stopPropagation();
return false; 
Run Code Online (Sandbox Code Playgroud)

在你的事件处理程序中

  • `return false`与调用`e.stopPropagation()`*和*`e.preventDefault()`相同. (2认同)