如何停止传播绑定函数而不是整个事件? [英] How to stop propagation of a bound function not the entire event?

查看:23
本文介绍了如何停止传播绑定函数而不是整个事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到许多元素的点击功能.有时这些元素可能会相互重叠.因此,单击事件绑定到子项,也绑定到其父项.该方法特定于单击的元素.自然,由于事件冒泡,孩子的事件首先被触发,然后是父母.我不能让他们同时被调用,因为父母事件覆盖了孩子的事件.所以我可以使用 event.stopPropagation() 以便只有点击的第一个元素接收事件.问题是元素上还附加了其他单击事件,例如,我在这些元素上使用了 jQuery 的可拖动事件.如果我停止点击事件的传播,则draggable 不起作用,并且不会调用以下点击事件.

所以我的问题是:有没有办法阻止事件将调用的方法而不是整个事件的事件冒泡?


才华横溢的约翰,但问题来了:

<div class="Elmchildren"></div><!--绝对--><div class="Elmchildren"></div><!--绝对--><div class="Elmchildren"></div><!--绝对--><div id="Elm2"><!--相对--><div class="Elmchildren"></div><!--绝对--><div class="Elmchildren"></div><!--绝对--><div class="Elmchildren"></div><!--绝对-->

Click 事件绑定到 #Elm1#Elm2..Elmchildren 是宽度和高度 100%.所以他们实际上是当前的目标.

解决方案

尝试这样的事情

$(mySelector).click(function(evt) {如果(evt.target == evt.currentTarget){///运行你的代码.if 语句只会在目标元素上运行这个点击事件///所有其​​他点击事件仍将运行.}});

I have a click function bound to many elements. It is possible that sometimes these elements may sit within one another. So, the click event is bound to a child and also bound to its parent. The method is specific to the element clicked. Naturally, because of event bubbling, the child's event is fired first, and then the parents. I cannot have them both called at the same time because the parents event overwrites the event of the child. So I could use event.stopPropagation() so only the first element clicked receives the event. The problem is that there are other click events also attached to the element, for example, I am using jQuery's draggable on these elements. If I stop the propagation of the click event, then draggable doesn't work, and the following click events are not called.

So my question is: Is there a way to stop the event bubbling of the method the event will call and not the entire event?


Brilliant John, but here is the problem:

<div id="Elm1"><!-- relative -->
 <div class="Elmchildren"></div><!-- absolute-->
 <div class="Elmchildren"></div><!-- absolute-->
 <div class="Elmchildren"></div><!-- absolute-->

 <div id="Elm2"><!-- relative -->
  <div class="Elmchildren"></div><!-- absolute-->
  <div class="Elmchildren"></div><!-- absolute-->
  <div class="Elmchildren"></div><!-- absolute-->
 </div>

</div>

Click event is bound to #Elm1 and #Elm2. The .Elmchildren are width and height 100%. So they are actually the current targets.

解决方案

try someting like this

$(mySelector).click(function(evt) {
  if (evt.target == evt.currentTarget) {
      ///run your code.  The if statment will only run this click event on the target element
      ///all other click events will still run.
  }
});

这篇关于如何停止传播绑定函数而不是整个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆