jQuery/Javascript确认出现两次
出于某种奇怪的原因,我的确认框出现了两次。这是我的密码:jQuery/Javascript确认出现两次,javascript,jquery,confirm,Javascript,Jquery,Confirm,出于某种奇怪的原因,我的确认框出现了两次。这是我的密码: $(".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{
$(".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;
}
});
是否尝试删除未使用的
var confirm
?是否动态加载任何内容(通过ajax)?可能是click事件绑定到同一元素两次,导致双重确认。尝试以下操作:
$_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
}
}
});
当我们在通过AJAX动态加载的元素上绑定事件时,就会发生这种情况 例如,我们在点击
edit
form按钮时加载一些动态html内容(例如模态中的动态内容)
在该内容中,如果我们在某个按钮上有绑定的click事件,例如删除
按钮,那么每次我们单击编辑
表单按钮,它都会将click
事件绑定到删除
按钮,
如果您在delete
按钮的点击事件上设置了确认框,它将询问您该点击事件的绑定次数这意味着如果我们点击了edit
表单按钮5次,它将要求您确认5次
因此,为了解决该问题,您可以在每次将事件绑定到动态加载的元素之前,取消绑定该事件,如下所示:
$(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;
}
或者解决此问题的另一种方法是在主页中添加脚本,这意味着静态页面不在stopPropagation()上的jQuery doc动态加载的页面中。“注意,这不会阻止同一元素上的其他处理程序运行”,因此如果“单击”绑定两次,确认对话框仍会显示两次。确定,我同意你的看法,在这种情况下是没有用的。最好让示例修改脚本。是否需要返回false?@billrichards是,因为它需要事件的默认操作不会被触发。但是最好使用event.preventDefault();