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

て烟熏妆下的殇ゞ 提交于 2019-12-18 13:53:26

问题


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 button also with click() event to close the content. This close button is only visible by clicking on the big header.

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

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


回答1:


You need to stop the event from propagating up the DOM tree:

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

    // Your code here
});



回答2:


$('.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,




回答3:


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



来源:https://stackoverflow.com/questions/7835775/how-to-prevent-a-click-event-through-a-child-div-to-a-parent-div-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!