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

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

我的代码:

 

当点击.popup-content ,当我不希望#popup的孩子这样做时,它会触发click事件。

jQuery代码:

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

尝试:

 e.stopPropagation(); return false; 

在你的事件处理程序中

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

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

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

 $('.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?"); }); 
 {if(e.target == this ){ return;}});