Javascript JQuery事件.stopPropagation()不工作
在我的html中,我在一个li中嵌入了一系列的类dragHandleJavascript JQuery事件.stopPropagation()不工作,javascript,jquery,Javascript,Jquery,在我的html中,我在一个li中嵌入了一系列的类dragHandle <div class='treeView'> <ul class='tree'> <li><span class="dragHandle"></span>Item 1 <ul> <li><span class="dragHandle"></span
<div class='treeView'>
<ul class='tree'>
<li><span class="dragHandle"></span>Item 1
<ul>
<li><span class="dragHandle"></span>Item 2 <a href="#">link</a></li>
</ul>
</li>
</ul>
当我将鼠标向下和向上移动到元素上时,我会得到向下和向上的警报,但是我也会得到li的事件处理程序的点击警报。我认为应该通过在mousedown和mouseup处理程序中调用event.stopPropagation来防止这种情况。如何停止为dragHandle上的mousedown/up事件调用click事件
蒂亚,
亚当
如何停止为dragHandle上的mousedown/up事件调用click事件
你捕获。。。吃。。。该活动:
这里的关键是,
单击
,鼠标向下
,以及mouseup
是不同的事件。虽然您可能会认为单击
是一个鼠标向下
,然后是一个mouseup
,但实际上您可能会遇到由用户操作触发的单击
事件,这些用户操作甚至不涉及鼠标,以及mousedown
和mouseup
的组合,它们根本不会导致任何单击事件。您可以创建一个简单的包装器-“类”,用于跟踪鼠标向下和向上的事件:
(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引用是可以接受的。为此干杯,我考虑将单击事件视为鼠标向下和鼠标向上。
$(".dragHandle").click(function(event) { event.stopPropagation(); });
(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);
});
})();