2009-07-26 4 views
12

내 HTML에는 li 클래스에 dragHandle 클래스가 포함되어 있습니다.JQuery event.stopPropagation() not working

$(".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과 요소 위에서 마우스까지 내가 상하로 알림을받을 그러나 나는 또한 리튬의의 클릭 경고를 얻을 다음과 같이

<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를 사용하여 이벤트 핸들러를 첨부 이벤트 처리기도 있습니다. mousedown 및 mouseup 핸들러의 event.stopPropagation 호출로 인해이를 막아야한다고 생각했습니다. dragHandle에서 mousedown/up 이벤트에 대해 호출되는 클릭 이벤트를 중지하려면 어떻게합니까?

은 TIA, 아담은

답변

16

은 어떻게 dragHandle에 mousedown/최대 이벤트 호출되는 클릭 이벤트를 중지합니까?

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

여기서 핵심은 click, mousedownmouseup이 별개의 사건이라는 것이다 :

당신은 이벤트 ... 캡처 ... 먹는다. clickmousedown이고 그 뒤에 mouseup이 있다고 생각할 수도 있지만 실제로는 마우스가 포함되지 않은 사용자 작업에 의해 트리거 된 click 이벤트와 mousedownmouseup의 조합으로 인해 발생하는 이벤트가있을 수 있습니다. 모든 click 이벤트. 이것은 폐쇄 및 위임 DragDropHandler 객체에 이벤트 처리를 생성

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

:

+0

건배, 나는 mousedown 및 마우스로 클릭 이벤트를 고려하고있었습니다. – apchester

3

당신은 간단한 wrapper- 마우스 다운 추적 "클래스", 이벤트까지를 만들 수 있습니다. 이 메소드 내부의 DragDropHandler 객체를 참조하는지 확인하기 위해 function.call (첫 번째 매개 변수는 컨텍스트)을 사용했습니다. 전역 공간에서 도달 할 수없는 익명의 함수를 작성 했으므로, 래퍼 이벤트 핸들러 내에서 DragDropHandler 참조를 사용하는 것이 허용 가능하다고 생각합니다.