2011-03-08 80 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"); 
    }); 

一個更好的解決方案可能是接受點擊一些參數和檢查參數來決定要如何迴應。

相關問題