1

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

$("#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
});
4

5 回答 5

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/

Here's how you could use stopPropagation() instead:

<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/

于 2013-08-21T20:48:02.767 回答
1

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

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

jsFiddle 示例

于 2013-08-21T20:34:53.723 回答
0
$("#buttons").on("click", "button, button.red", function(){
    // if this one happens, don't do the above one
});
于 2013-08-21T20:35:51.167 回答
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/

于 2013-08-21T20:38:50.000 回答
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;
     }
});
于 2013-08-21T20:43:16.467 回答