2015-11-15 108 views
2

在我的jQuery代碼中,我無法保持正確的執行順序。我環顧四周,發現使用setTimeout()是一種選擇,但我不確定在哪裏使用。代碼的當前結構是像下面setTimeout()維護jQuery執行順序

$(document).ready(function(){ 
    $('#search-submit').on('click', function(){ 
    var keyword = $('#search-input').val(); 
    $(".loading").show(); 

    setTimeout(function() { 
     if(){ 
     //some conditions and calls to post 
     } 
     $(".loading").hide(); 
    }, 0); 
    } 
    } 

if塊完成執行之後的應hide()生效,但現在它直接隱藏元件。

+1

給予'的setTimeout()'的東西多'0' – Ramanlfc

回答

0
$(document).ready(function(){ 
    $('#search-submit').on('click', function(){ 
    var keyword = $('#search-input').val(); 
    $(".loading").show(); 

    if(){ 
     //some conditions and calls to post 
    } 

    setTimeout(function() { 
     $(".loading").hide(); 
    }, 1500); 
    } 
} 
+0

至少說幾句話 – kaveman

1

事實上,jQuery有使事情的同步更精細的方式:你在這裏做什麼

$(function() { 

    $('#search-submit').on('click', function(){ 

     var keyword = $('#search-input').val(); 

     $('.loading').show().queue(function() { 

      if (...) { 
      //some conditions and calls to post 
      } 

      $(this).dequeue(); 

     }).queue(function() { 

      $(this).hide().dequeue(); 
     }); 
    }); 
});