2011-03-08 83 views
2

如果一个事件发生可能会阻止他人提高吗?如何防止事件发生?

Example on jsFiddle

$(window).click(
    function(e) 
    { 
     $("#out").html("preventing next event from happening\n"); 
    }); 

$(window).click(
    function(e) 
    { 
     $("#out").html($("#out").html() + "evil event should not write here"); 
    }); 
+0

事件的顺序并不重要。重要的是,如果一个人执行其他人不这样做。 – BrunoLM 2011-03-08 21:53:46

+0

http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery – n00b 2011-03-08 21:56:34

回答

4
$(window).click(
    function(e) 
    { 
     $("#out").html("preventing next event from happening\n"); 
     e.stopImmediatePropagation(); 
    }); 

$(window).click(
    function(e) 
    { 
     $("#out").html($("#out").html() + "evil event should not write here"); 
    }); 

http://api.jquery.com/event.stopImmediatePropagation/ - 在这里阅读更多

3

好了,你可以使用preventDefault()以阻止发生的其他事件。然而,这对您的解决方案来说可能过于矫枉过正,因为它并不真正让您选择哪个事件触发。

http://jsfiddle.net/c52Wr/1/

$(window).click(
    function(e) 
    { 
     $("#out").html("preventing next event from happening\n"); 
     e.preventdefault(); 
    }); 

$(window).click(
    function(e) 
    { 
     $("#out").html($("#out").html() + "evil event should not write here"); 
    }); 

一个更好的解决方案可能是接受点击一些参数和检查参数来决定要如何回应。

相关问题