一个元素上的两个听众:只让一个人开火

时间:2013-08-21 20:32:58

标签: javascript jquery events event-handling

在多个事件处理程序对单个元素和操作进行操作的情况下,如何强制仅触发其中一个事件? JSFiddle

$("#buttons").on("click", "button", function(){
    // only do this if the event below isn't fired
});
$("#buttons").on("click", "button.red", function(){
    // if this one happens, don't do the above one
});

5 个答案:

答案 0 :(得分:4)

对于更通用的解决方案,event.stopImmediatePropagation()将阻止事件触发更多处理程序。对于绑定到同一元素的处理程序,它们绑定的顺序似乎很重要。您还可以将有条件地不想触发的那个绑定到DOM中更高的元素并使用e.stopPropagation()

$(document).ready(function(){
    $("#buttons").on("click", ".red", function(e){
        e.stopImmediatePropagation();
        $(this).css("color","red");
    });
    $("#buttons").on("click", "button", function(){        
        $(this).css("background","blue");
    });
});

http://jsfiddle.net/Ef5p7/

以下是您可以使用stopPropagation()的方式:

<div id="buttonsOuter">
    <div id="buttons">
        <button>turn blue</button>
        <button class="red">only turn text red</button>
        <button>turn blue</button>
        <button>turn blue</button>
        <button>turn blue</button>
    </div>
</div>

...

$(document).ready(function () {
    $("#buttons").on("click", ".red", function (e) {
        e.stopPropagation();
        $(this).css("color", "red");
    });
    $("#buttonsOuter").on("click", "button", function () {
        $(this).css("background", "blue");
    });
});

http://jsfiddle.net/CwUz3/

答案 1 :(得分:1)

将第一个事件处理程序更改为:

$("#buttons").on("click", "button", function(){
    $(this).not('.red').css("background","blue");
});

<强> jsFiddle example

答案 2 :(得分:0)

$("#buttons").on("click", "button, button.red", function(){
    // if this one happens, don't do the above one
});

答案 3 :(得分:0)

尝试使用:not() http://api.jquery.com/not-selector/

$(document).ready(function(){
    $("#buttons").on("click", "button:not(.red)", function(){
        $(this).css("background","blue");
    });
    $("#buttons").on("click", "button.red", function(){
        $(this).css("color","red");
    });

});

这是工作小提琴: http://jsfiddle.net/SpFKp/4/

答案 4 :(得分:0)

试试这个,会调用这些函数,但你可以添加条件来不运行代码:

var functionCalledFlag =false;
$("#buttons").on("click", "button", function(){
        if(!functionCalledFlag ){
           functionCalledFlag =true;
       // only do this if the event below isn't fired
     }else{
       functionCalledFlag =false;
     }

});
$("#buttons").on("click", "button.red", function(){
    if(!functionCalledFlag ){
           // only do this if the event above isn't fired
       functionCalledFlag =true;
     }else{
       functionCalledFlag =false;
     }
});