我有一个选择器绑定一个将删除弹出窗口的click事件。但是,我只希望选择器处理单击,而不是选择器的子节点才能触发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>
点击.popup-content
时,如果我不希望#popup
的孩子这样做,它会触发点击事件。
jQuery代码:
$('#popup').bind('click', function()
{
$(this).remove();
});
答案 0 :(得分:17)
在#popup
的事件处理程序中,检查e.target == this
。即:
$('#popup').bind('click', function(e) {
if(e.target == this) $(this).remove();
});
这样做比将额外的点击处理程序绑定到所有孩子要容易得多。
答案 1 :(得分:14)
尝试:
e.stopPropagation();
return false;
在您的事件处理程序
中答案 2 :(得分: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?");
});
答案 3 :(得分:0)
{if(e.target == this ){ return;}});