我有一个删除按钮来删除照片。第一次点击会在顶部为div
设置动画,并显示以下消息:“如果您确实要删除此照片,请再次点击。”第二次单击会删除照片。如果您在第一次单击后3秒内未再次单击,则该消息将消失。但是如果它消失并再次单击该按钮,它仍将被删除。我需要在消息消失时停止脚本以停止发布$.ajax()
$(".delete").toggle(function(){
$("#top").html("Click again if you really want delete this photo.");
$("#top").animate({top: "0"}).delay(3000).animate({top: "-50"});
return false;
}, function() {
$("#top").animate({top: "-50px"});
var id = $(this).attr("id");
$.ajax({
...
});
});
答案 0 :(得分:4)
像这样(未经测试):
$(".delete").click(function()
{
if ($(this).attr('canDelete') == 'y')
{
$("#top").animate({top: "-50px"});
... do delete
}
else
{
$("#top").html("Click again if you really want delete this photo.");
$("#top").attr('canDelete', 'y')
.animate({top: "0"})
.delay(3000)
.attr('canDelete', 'n')
.animate({top: "-50"});
}
});
答案 1 :(得分:3)
为什么不做这样的事情?
$(".delete").click(function() {
if ( $(this).hasClass("confirm") ) {
//When the button is clicked again within 3 seconds it will have
//the confirm class and will go here
} else {
//The button will go here when clicked first time, a class
//of confirm is added for 3 seconds.
$(this).addClass("confirm");
setTimeout(function() {
$(this).removeClass("confirm");
}, 3000);
}
});
答案 2 :(得分:1)
你可以像这样在闭包中放一个变量:
var allowDel;
$(".delete").toggle(function(){
allowDel = true;
$("#top").html("Click again if you really want delete this photo.");
$("#top").animate({top: "0"}).delay(3000).animate({top: "-50"});
setTimeout(function() { allowDel = false; }, 3000);
return false;
}, function(){
if (!allowDel) return;
$("#top").animate({top: "-50px"});
var id = $(this).attr("id");
$.ajax({
...
});
});
答案 3 :(得分:0)
另一个解决方案,这次没有任何额外的变量或属性/属性(不是说有任何显着的优势,可能是一个更清洁)。这个使用消息DIV的Y坐标来确定是否允许删除。
演示: http://jsfiddle.net/Eu2vu/
<强>代码:强>
$(".delete").click(function() {
var top = $('#top');
if (top.position().top >= 0) {
top.animate({top: "-50px"});
console.log('do delete');
}
else {
top.html("Click again if you really want delete this photo.");
top.animate({top: "0"}).delay(3000).animate({top: "-50"});
}
});
答案 4 :(得分:0)
所以我编辑它,它的工作原理
var allowDel;
$(".delete").click(function(){
if(allowDel){
$.ajax();
allowDel = false;
}else{
allowDel = true;
setTimeout(function() {
$("#top").slideUp();
}, 3000);
return false;
}
});