2012-07-18 24 views
1

我有一個刪除按鈕來刪除照片。第一次點擊動畫div最上面的消息:「如果你真的想刪除這張照片再次點擊。」再次點擊刪除照片。如果您在第一次點擊後不再點擊3秒,消息將消失。但是如果它消失並且您再次點擊該按鈕,它仍然會被刪除。我需要停止腳本時消息即消失停止後$.ajax()jQuery按鈕超時

$(".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({ 
      ... 
     }); 
}); 

回答

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

爲什麼不這樣做?

$(".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); 

    } 
}); 
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"}); 
    } 
}); 
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"}); 
    } 
}); 
0

所以我編輯它和它的作品

var allowDel; 
$(".delete").click(function(){ 
    if(allowDel){ 
     $.ajax(); 
     allowDel = false; 
    }else{ 
     allowDel = true; 
     setTimeout(function() { 
      $("#top").slideUp(); 
     }, 3000); 
     return false; 
    } 
});