Jquery 防止从子级触发父级单击事件中单击
我有一个选择器,它绑定一个点击事件,该事件将删除弹出窗口。但是,我只希望选择器处理单击,而不是希望选择器的子级能够触发单击事件 我的代码:Jquery 防止从子级触发父级单击事件中单击,jquery,click,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 du
<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').bind('click', function(e)
{
e.stopPropagation();
});
或
在您的情况下,这是相同的,但有时如果没有e.stopPropagation(),您就无法完成这类工作。例如:
$('.popup-content a').bind('click', function(e)
{
e.stopPropagation();
return confirm("Are you sure?");
});
在
#弹出窗口的事件处理程序中
检查e.target==this
。i、 e:
$('#popup').bind('click', function(e) {
if(e.target == this) $(this).remove();
});
这样做比将额外的点击处理程序绑定到所有子项要容易得多。可能重复的
返回false
与调用e.stopPropagation()
和e.preventDefault()
。啊,我不太了解stopPropagation
的用法,谢谢+1,谢谢,我也不知道stopPropagation()
e.当链接是具有click事件的元素的父元素时,stopPropagation不起作用。防止默认值和返回false是有效的。感谢男士:)感谢您提供了另一个处理父单击的示例,但允许孩子拥有自己的处理程序。这正是我需要检查的。我使用了if(!$(e.target).is('a'))
而不是if(e.target==this)
,但这使我走上了正确的道路。我还需要使用if(!$(e.target).is('a')。我在'each'函数中使用了它(可能使用循环确定解决方案)
{if(e.target == this ){ return;}});
$('.popup-content a').bind('click', function(e)
{
e.stopPropagation();
return confirm("Are you sure?");
});
$('#popup').bind('click', function(e) {
if(e.target == this) $(this).remove();
});
{if(e.target == this ){ return;}});