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

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

问题描述

我有一个绑定到许多元素的点击功能。有时这些元素可能彼此坐在一起。因此,click事件绑定到子节点并绑定到其父节点。该方法特定于单击的元素。当然,由于事件冒泡,孩子的事件首先被解雇,然后是父母。我不能同时调用它们,因为父母事件会覆盖孩子的事件。所以我可以使用event.stopPropagation(),所以只有点击的第一个元素才会收到事件。问题是还有其他点击事件也附加到元素,例如,我在这些元素上使用jQuery的draggable。如果我停止传播click事件,则draggable不起作用,并且不会调用以下点击事件。

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,但这里是概率。

Brilliant John, but here is the prob.

<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>

点击事件绑定到#Elm1和#Elm2。 .Elmchildren的宽度和高度均为100%。所以它们实际上是目前的目标。

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

推荐答案

尝试这样的事情

$(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.
  }
});

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

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