如何防止事件升起?

时间:2011-03-08 21:53:13

标签: javascript jquery javascript-events

如果一个事件引发可能会阻止他人加薪吗?

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

2 个答案:

答案 0 :(得分: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/ - 点击此处了解更多

答案 1 :(得分: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");
    });

更好的解决方案可能是接受点击和一些参数,并检查该参数以决定您的回应方式。