2012-01-27 31 views
2

第一端我有以下代碼...防止第二次執行,直到jQuery的

$("#myID").click(function(){ 

    //do some ajax requisition here 
    //make it appears in screen with a fadeIn(300) 

}); 

#myID是一個標籤

的ID,但我需要這個功能並沒有再次調用,直到實際的執行結束了,我試着在註釋之前放置了許多不同的代碼,但沒有成功,如果你能幫助我阻止第二次執行!

fadeIn()不包含執行,它在執行效果發生時執行後的代碼,有人可以幫助我嗎?

謝謝

+0

什麼類型的元素是myID?另外,您是否可以包含所有代碼,而不是在評論中總結它? – JohnFx 2012-01-27 17:40:20

+0

evandrobm 2012-01-27 17:41:08

回答

1

它有可能殺死以前的ajax,或者你可以創建一個運行的布爾值,當有人點擊你將其設置爲true,並且你有一個if(!running){//做ajax},在ajax的回調您將運行到假

+0

作品,感謝的人,解決方案非常簡單,但我在它的小時,並沒有解決問題,非常感謝你! – evandrobm 2012-01-27 17:49:28

0

使用同步AJAX調用(默認爲異步)。有關如何做到這一點的詳細信息,請參閱this question

+0

我使用$ .getJSON(url,,function(data){...});對於ajax請求... – evandrobm 2012-01-27 17:44:30

+0

以下是描述如何同步使用getJSON的博客文章:http://www.nurelm.com/themanual/2010/08/09/self-indulgent-code-jquery-getjson-with-error -handling/ – JohnFx 2012-01-27 17:46:48

+3

我建議不要做同步AJAX調用。它會鎖定瀏覽器直到完成。 – 2012-01-27 17:47:54

4

您可以設置存儲AJAX功能是否正在運行的狀態的標誌:

$(function() { 

    //set flag to allow AJAX calls 
    var AJAX_ok = true; 

    //bind click event handler 
    $("#myID").click(function(){ 

     //check if it is ok to run an AJAX request right now 
     if (AJAX_ok === true) { 

      //if we can run an AJAX request then set the AJAX_ok flag to false so another one does not start 
      AJAX_ok = false; 

      //make the AJAX call 
      $.getJSON('<url>', function (data) { 

       //now that the callback function has been called, the AJAX call is done, so we re-enable the AJAX_ok flag 
       AJAX_ok = true; 

       //make it appears in screen with a fadeIn(300) 
       //if DATA is valid HTML then... 
       $(data).css('display', 'none').appendTo('#some-container').fadeIn(300); 
      }); 
     } 
    }); 
}); 

這將只運行在#myID元素的click事件處理一個AJAX調用一次。

0

大概有100點更好的方法,但是......

$("#myID").click(function() { 
    var is_running = $(this).data('running'); 

    if (!is_running) 
     $(this).data('running', true); 
    else 
     return; 

    /* Do stuff */ 

    $(this).data('running', false); 
} 
0

使用回調,以確保執行順序。

$("#myID").click(function(){  
    $.ajax({ 
     url: 'whatever url you are calling', 
     success: function(){ 
      alert('ajax done'); 
      $('whatever "it" is').fadeIn(300, function(){ 
       //code place here will not execute until after fade in 
       alert('fadeIn done'); 
      } 
     } 
    }) 
});