【问题标题】:How can I override a jQuery event handler of an id selector with a class selector?如何使用类选择器覆盖 id 选择器的 jQuery 事件处理程序?
【发布时间】:2012-02-18 22:38:13
【问题描述】:

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

如何用第二个 sn-p 覆盖第一个 sn-p 中的处理程序?

【问题讨论】:

    标签: javascript jquery event-handling jquery-selectors jquery-events


    【解决方案1】:

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

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

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

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

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

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

    【讨论】:

      【解决方案2】:

      您可以使用.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();
          });
      });
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-15
        • 2013-03-01
        • 1970-01-01
        • 2016-05-02
        • 1970-01-01
        • 2019-07-30
        • 2017-01-17
        • 1970-01-01
        相关资源
        最近更新 更多