【问题标题】:jQuery/Javascript confirm coming up twicejQuery/Javascript 确认出现两次
【发布时间】:2009-11-26 01:55:51
【问题描述】:

出于某种奇怪的原因,我的确认框出现了两次。这是我的代码:

$(".DeleteComment").live("click", function(){

    var CommentID = $(this).attr("rel");
    var confirm

    if (!confirm('Are you sure you want to permanently delete this comment?')){

        return false;

    }else{
        $(this).html("loading").css("color", "#999");
        //AJAX HERE
        return false;
    }


});

【问题讨论】:

    标签: javascript jquery confirm


    【解决方案1】:

    您是否动态加载任何内容(通过 ajax)?可能是点击事件两次绑定到同一个元素,导致双重确认。

    【讨论】:

      【解决方案2】:

      试试这个:

      $_blockDelete = false;
      
      $(".DeleteComment").live("click", function(event){
      
          event.preventDefault();
          //event.stopPropagation(); // it is not necessary
      
          if (!$_blockDelete)
          {
            $_blockDelete  =true;
            var rconfirm = confirm('Are you sure you want to permanently delete this comment?');
            if (rconfirm)
            {
                $(this).html("loading").css("color", "#999");
                var CommentID = $(this).attr("rel");
                //AJAX HERE
                //return the value "false" the variable "$_blockDelete" once again ajax response
      
            }
          }
      
      });
      

      【讨论】:

      • from jQuery doc on stopPropagation() “请注意,这不会阻止同一元素上的其他处理程序运行”,因此如果“单击”被绑定两次,确认对话框仍将显示两次。跨度>
      • 好的,我同意你的观点,在这种情况下不会有用。最好离开示例修改脚本。
      • 是否需要return false?
      • @billrichards 是的,因为它需要事件的默认动作不会被触发。但最好使用 event.preventDefault();
      【解决方案3】:

      当我们在通过 AJAX 动态加载

      的元素上绑定事件时会发生这种情况

      例如,我们在点击 edit 表单按钮时加载一些动态 html 内容(例如模态中的动态内容),

      如果我们在该内容中 在某个按钮上绑定了点击事件,例如delete 按钮,那么我们每次点击edit 表单按钮,每次都会将click 事件绑定到delete 按钮,

      如果你在delete按钮的点击事件上设置了确认框,那么它会询问你为该点击事件绑定的次数意味着如果我们点击了@987654327 @表单按钮 5 次然后它会要求您确认 5 次。

      所以为了解决这个问题你可以在每次绑定事件之前unbind事件动态加载元素如下:

      $(document).off('click', '.DeleteComment').on('click', '.DeleteComment', function () {
         if (confirm('Are you sure you want to permanently delete this comment?')){
            //Delete process
            return true;
         }
         return false;
      }
      

      或者解决这个问题的另一种方法是在主页面中添加你的脚本,这意味着静态页面不是动态加载的

      【讨论】:

        【解决方案4】:

        您是否尝试删除未使用的var confirm

        【讨论】:

          猜你喜欢
          • 2016-05-05
          • 2013-02-28
          • 1970-01-01
          • 2014-01-20
          • 1970-01-01
          • 1970-01-01
          • 2016-09-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多