我有一个链接,用户单击该链接即可删除记录 (class="delMail"
)。当他们单击此链接时,会显示一个新的 div,其中还有 2 个链接 [Y 和 N]。单击 Y 将删除他们的电子邮件,单击 N 将取消请求。
问题是,如果用户在单击 Y/N 之前单击 delMail 链接 10 次,代码也会尝试删除电子邮件 10 次?
我已将代码更新为工作版本,如下:
$(function(){ //delete Message
$("a.delMail").click(function(e) {
e.preventDefault();
//get divs to show and hide
var $confirmDelDiv = $(this).parents("tr").next().find(".confirmDelete");
var $replyDiv = $(this).parents("tr").next().next().find(".replyDiv");
$replyDiv.fadeOut(); //hide reply div
$confirmDelDiv.fadeIn("slow"); //show confirm message
//get id
var $id = $(this).attr("href"); //get id value of email
var dataString = "id="+$id;
$("a.delLinkYes").click(function(y){//if user confirms delete, send id to php page
y.preventDefault(); $(this).unbind("click");
$.ajax({
type: "POST",
url: "process.php",
action: "deleteEmail",
data: dataString,
dataType: "JSON",
cache: false,
success: function(data){
if(data == "true"){//if email was successfully deleted
$confirmDelDiv.delay(60).append("Email deleted!");
$confirmDelDiv.fadeOut("slow");
}else{$confirmDelDiv.delay(60).append("Error deleting this email. Please try again!"); return false;}
}
});
return false;
});
$("a.delLinkNo").click(function(n){//if user cancels request, stop.
$(this).unbind("click");alert("cancel"); return false;
//$confirmDelDiv.fadeOut("slow"); return false;
});
});
});
这样可以吗?我的意思是效率方面?
最佳答案
我会考虑使用 jQuery.fn.one()
而不是 jQuery.fn.click()
。从文档中可以看出,您可以:
Attach a handler to an event for the elements. The handler is executed at most once per element.
所以它应该像替换一样简单:
$("a.delMail").click(function(e) ...
与:
$("a.delMail").one('click', function(e) ...
关于javascript - 如何使事件单击事件在多次单击元素时仅触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5114811/