2009-07-26 119 views
12

在我的html中,我有一个类的dragHandle范围内嵌入一个李。JQuery event.stopPropagation()不起作用

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

附上使用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和鼠标了元素上,我得到了下来,警报,但是我也得到了李的的点击警报事件处理程序。我认为这应该通过调用mousedown和mouseup处理程序中的event.stopPropagation来阻止。如何停止在dragHandle上调用mousedown/up事件的点击事件?

TIA, 亚当

回答

16

如何停止被要求对dragHandle鼠标按下/上事件的单击事件?

您捕捉......吃...... 事件:

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

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

+0

干杯,我正在考虑点击事件作为mousedown和鼠标。 – apchester 2009-07-27 09:08:34

3

您可以创建一个简单的wrapper-“类”,即跟踪鼠标按下和最多事件:

(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引用是可以接受的。