Javascript 如何用类选择器重写id选择器的jQuery事件处理程序?

Javascript 如何用类选择器重写id选择器的jQuery事件处理程序?,javascript,jquery,event-handling,jquery-selectors,jquery-events,Javascript,Jquery,Event Handling,Jquery Selectors,Jquery Events,我为几个具有id和类选择器的元素提供了单击事件处理程序: $(function() { $("#cancelOrderLink").click(function() { if (confirm("If you continue, all items will be removed " + "from your cart. This action cannot be undone. Continue " + "and empt

我为几个具有id和类选择器的元素提供了单击事件处理程序:

$(function() {
    $("#cancelOrderLink").click(function() {
        if (confirm("If you continue, all items will be removed " +
            "from your cart. This action cannot be undone. Continue " +
            "and empty cart?"))
            $("form#clearCartForm").submit();
    });

    $(".updateItemLink").click(function(){
        $(this).closest("form").submit();
    })
});
但是,我想添加逻辑,以防止在元素具有特定类名时触发这些处理程序:

$(function() {
    $(".superUser").click(function() {
        $("#message").html("This action is not allowed when acting as a Super User.<br />");

        return false;
    });
});
$(函数(){
$(“.superUser”)。单击(函数(){
$(“#message”).html(“作为超级用户时不允许此操作。
”; 返回false; }); });

如何用第二个代码段覆盖第一个代码段中的处理程序?

Add
event.stopPropagation()到您的代码:

$(".superUser").click(function(e) {
   e.stopPropagation();
   ...
或者,如果元素相等,并且没有任何其他
侦听器,请取消绑定上一个方法:

$(".superUser").unbind('click').click(function() {
如果要在运行时为特定ID绑定事件,但不绑定类名,请使用:

$("#cancelOrderLink").not('.superuser').click(function() {
您可以使用过滤器


我建议使用“return false”代替e.stopPropagation()。这是一种更简单的停止传播和防止默认值的方法。 例如:

$("#yourclass").click(function(){
return flase;
});

想想你需要什么。stopPropagation正是所需要的,因为您不想让该事件进一步冒泡,在这种情况下,除了停止传播(通过调用完全相同的函数)之外,还不需要return false做的其他事情。(它还停止回调执行)读取此链接:!
$("#yourclass").click(function(){
return flase;
});