如何用类选择器覆盖id选择器的jQuery事件处理程序

How can I override a jQuery event handler of an id selector with a class selector?

本文关键字:选择器 jQuery 事件处理 程序 id 何用类 覆盖      更新时间:2023-09-26

我有几个带有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;
    });
});

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

event.stopPropagation();添加到代码中:

$(".superUser").click(function(e) {
   e.stopPropagation();
   ...

或者,如果元素相等,并且没有任何其他click侦听器,则取消绑定前面的方法:

$(".superUser").unbind('click').click(function() {

如果您想在运行时为特定ID绑定事件,而不是为类名绑定事件,请使用:

$("#cancelOrderLink").not('.superuser').click(function() {

您可以使用.not()过滤器。

$(function() {
    $("#cancelOrderLink").not(".superUser").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();
    });
});

我建议使用"return false"而不是e.stopPropagation()。这是一种更简单的方法来停止传播并防止默认值。例如:

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