jQuery:如何停止绑定函数的传播而不是整个事件?

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

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


很棒的约翰,但这是问题。

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

尝试像这样

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

建议的解决方案

 evt.target == evt.currentTarget 

很好,但有些情况下它没有帮助。

示例:具有嵌套ul / li列表的(suckerfish样式)菜单结构。
mousemove事件来自列表项内的链接,该列表项是ul-list的子项,也是另一个列表项的子项。 典型的带子菜单的html菜单结构。
evt.target将是链接标记,但我们对列表项上的mousemove感兴趣。
更糟糕的是:链接标记可能包含span或img标记或其他嵌套的东西。 然后evt.target将是这个跨度或img。

这里似乎有用的是在父/根项上捕获事件,然后检查evt.target的父项。

像这样(使用jQuery),

 var $menu = $('div#menu'); $('body').mousemove(function(evt){ var element = evt.target; // find the deepest list item that was affected by this mouseover event. var list_item; var in_menu = false; while (element) { if (element == $menu[0]) { in_menu = true; break; } else if (!list_item && element.tagName == 'LI') { // we found a list item, but we are not sure if we are inside the menu tree. list_item = element; } } // do something with the result. if (!in_menu) { .. // close all submenus } if (list_item) { .. // open the submenu for this list item. } else { // mouse in menu, but not hovering an item. // leave the submenus open. (?) } }); 

也许其中一些可以缩写为jQuery,如$(evt.target).parents()。是($ menu),但我没有得到这个工作。 另外,我猜这个带有element.tagName的显式循环更快。

Interesting Posts