首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >防止从子触发父单击事件中单击

防止从子触发父单击事件中单击
EN

Stack Overflow用户
提问于 2011-08-03 23:39:41
回答 4查看 16K关注 0票数 12

我有一个选择器,绑定一个点击事件,这将删除弹出。但是,我只想让选择器处理单击,而不是让选择器的子项能够触发单击事件。

我的代码:

代码语言:javascript
运行
复制
<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的子节点这样做时,它会触发click事件。

jQuery代码:

代码语言:javascript
运行
复制
$('#popup').bind('click', function()
{
    $(this).remove();
});
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-08-03 23:41:07

尝试:

代码语言:javascript
运行
复制
e.stopPropagation();
return false; 

在事件处理程序中

票数 14
EN

Stack Overflow用户

发布于 2012-06-05 20:20:34

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

代码语言:javascript
运行
复制
$('#popup').bind('click', function(e) {
    if(e.target == this) $(this).remove();
});

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

票数 17
EN

Stack Overflow用户

发布于 2011-09-26 00:24:36

代码语言:javascript
运行
复制
$('.popup-content').bind('click', function(e)
{
    e.stopPropagation();
});

代码语言:javascript
运行
复制
$('.popup-content').bind('click', function(e)
{
    return false;
});

在您的情况下-它是相同的,但有时您无法在没有e.stopPropagation()的情况下做这些事情。例如:

代码语言:javascript
运行
复制
$('.popup-content a').bind('click', function(e)
{
    e.stopPropagation();
    return confirm("Are you sure?");
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6929198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档