JQuery event.stopPropagation()不起作用

在我的html中,我有一个嵌入在li中的类dragHandle。

  • Item 1

我使用jQuery附加事件处理程序,如下所示:

 $(".tree li").click(function(event) { alert("click"); event.stopPropagation(); }); $(".dragHandle").mousedown(function(event) { alert("down"); event.stopPropagation(); }); $(".dragHandle").mouseup(function(event) { alert("Up"); event.stopPropagation(); }); 

当我mousedown并将鼠标放在元素上时,我得到了向下和向上警报,但是我也得到了li的事件处理程序的点击警报。 我认为应该通过调用mousedown和mouseup处理程序中的event.stopPropagation来防止这种情况。 如何停止在dragHandle上调用mousedown / up事件的click事件?

TIA,亚当

如何停止在dragHandle上调用mousedown / up事件的click事件?

你捕捉……然后吃…… 那个事件:

 $(".dragHandle").click(function(event) { event.stopPropagation(); }); 

这里的关键是clickmousedownmouseup是不同的事件。 虽然你可能会认为clickmousedown后跟一个mouseup ,但实际上你可能有用户操作触发的click事件甚至不涉及鼠标,以及mousedownmouseup组合不会导致任何click事件都可以。

你可以创建一个简单的包装器 – “类”,它跟踪鼠标按下和向上事件:

 (function () { var DragDropHandler = { isDrag: false, mouseDownHandler: function (event) { alert("down"); event.stopPropagation(); this.isDrag = true; }, mouseUpHandler: function (event) { alert("Up"); event.stopPropagation(); this.isDrag = false; }, clickHandler: function (event) { event.stopPropagation(); // Check if we've already received a mouseDown-event. If we have, // disregard the click event since we want drag-functionality if(this.isDrag) { return; } alert("click"); } }; $(".tree li").click(function(event) { DragDropHandler.clickHandler.call(DragDropHandler, event); }); $(".dragHandle").mousedown(function(event) { DragDropHandler.mouseDownHandler.call(DragDropHandler, event); }); $(".dragHandle").mouseup(function(event) { DragDropHandler.mouseUpHandler.call(DragDropHandler, event); }); })(); 

这将创建一个闭包并将事件处理委托给DragDropHandler对象。 请注意,我使用了function.call(第一个参数是上下文)来确保它引用其方法中的DragDropHandler对象。 由于我们创建了一个无法从全局空间到达的匿名函数,我认为在包装器事件处理程序中使用DragDropHandler引用是可以接受的。