在 jQuery 中,如何防止通过子 div 到父 div 的 click() 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7835775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:19:41  来源:igfitidea点击:

How to prevent a click() event through a child div to a parent div in jQuery?

jqueryeventsclick

提问by Paul Geisler

Situation:

情况:

<div class="header">
    <div style="float: left;" class="headerTitle">+ OPEN</div>
    <div class="closeBtn" style="float: right;">- CLOSE</div>
 </div> 
<div class="touristenContent">.....</div>

Visually:

视觉上:

|+Open..............................|-Close|..| (header)

|............Content..........................|

Header DIV is a 'big button' with jQuery click() event for opening the content. The close DIV is inside the big header DIV and represents the close buttonalso with click() event to close the content. This close buttonis only visible by clicking on the big header.

Header DIV 是一个“大按钮”,带有用于打开内容的 jQuery click() 事件。关闭 DIV 位于大标题 DIV 内,并表示关闭按钮也带有 click() 事件以关闭内容。这个关闭按钮只有通过点击大标题才能看到。

Clickng on the header and oppening the content works as expecting but clicking on the close buttonlet the click event through to the header DIV. The content closes and opens again beacause of two click events.

单击标题并打开内容按预期工作,但单击关闭按钮让单击事件通过标题 DIV。由于两次点击事件,内容关闭并再次打开。

So how can i design the whole thing properly to make the close buttonsolid and to prevent click through it to the header?

那么我怎样才能正确设计整个事情以使关闭按钮稳固并防止点击它到标题?

回答by Andy E

You need to stop the event from propagatingup the DOM tree:

您需要阻止事件向上传播DOM 树:

$('.closeBtn').click(function (evt) {
    evt.stopPropagation();

    // Your code here
});

回答by Val

$('.closeBtn').click(function (event){
   event.stopPropagation();
   //   ... your code here
   return false;
});

that should do the trick, so everytime you click on close it will not affect your header div,

这应该可以解决问题,因此每次单击关闭时,它都不会影响您的标题 div,

回答by hungryMind

Why not hook open event with <div style="float: left;" class="headerTitle">+ OPEN</div>instead of parent div. Otherwise return falseor stopPropagationfrom inner div click handler

为什么不使用<div style="float: left;" class="headerTitle">+ OPEN</div>而不是父 div挂钩打开事件。否则return falsestopPropagation从内部 div 单击处理程序