2011-04-21 91 views
0

嘿,所有!有關用戶顯示和JavaScript的快速問題。我想要做的是關閉更新箭頭gif,顯示旋轉的箭頭,做更新,隱藏旋轉的箭頭,最後顯示說這個項目現在設置的gif。通過三個循環循環 - 有些科室不改變

我的問題是旋轉的箭頭從不顯示。我把睡眠放在那裏,因爲我認爲更新發生得如此之快,以至於我沒有看到它,但似乎並非如此。

任何幫助非常感謝。

function sleep(milliSeconds){ 
    var startTime = new Date().getTime(); // get the current time 
    while (new Date().getTime() < startTime + milliSeconds); // hog cpu 
} 

function UpdateConfig(some_id) { 
    /* loop through all divs of class .changed_dropdown and if visible do something */ 
    $(".changed_dropdown").each(function(index) { 
     if($(this).is(":visible")){ 

      some_id = ($(this).data('some_id')); 
      /* turn off the div that shows this is in need of update (uparrow gif) */ 
      $('#changed'+some_id).toggle(false); 
      /* turn on the div that displays the arrows going around in a circle (roundarrow gif) */ 
      $('#updating'+some_id).toggle(true); 

      /* pause to allow the divs to change */ 
      sleep(500); 
      var new_config = $("#" + some_id).val(); 
      $.post("change_config.php?some_id="+some_id+"&config="+new_config); 

      /* turn off the div that displays the arrows going around in a circle (roundarrow gif) */ 
      $('#updating'+some_id).toggle(false); 
      /* turn on the gif that indicates this is the current setting */ 
      $('#unchanged'+some_id).toggle(true); 

     } 
    }); 
} 

回答

1

只要把最後兩行到傳遞進來的處理程序函數 「$。員額()」:

 $.post("change_config.php?some_id="+some_id+"&config="+new_config, {}, function() { 
     $('#updating'+some_id).toggle(false); 
     $('#unchanged'+some_id).toggle(true); 
    }); 

的 「$。員額()」 啓動HTTP請求,但它會立即返回。通過推遲第二批切換,直到完成,您讓其他事情發生,包括更新視圖。

編輯 —另一個問題(我敢肯定)是,你用一個非常可疑的方式使用該參數「some_id」。它是「UpdateConfig()」的參數,但是你所做的只是從存儲在一個元素上的某些數據重新分配它。但是因爲它被聲明爲而不是函數頂部的「.each()」循環的處理函數,所以它在每次迭代中都被真正共享,因此也被所有這些「$ .post()」處理程序共享。我不知道爲什麼它是一個參數,但它應該是安全的,簡單地改變該行地方它是從分配的「數據()」呼叫:

 var some_id = ($(this).data('some_id')); 

通過與var聲明它,你能在一個這個「.each()」回調的局部變量,所以每個「$ .post()」處理程序都有它自己的副本。

+0

這確實得到了旋轉箭頭來顯示,但現在處理程序中的切換不起作用。 – 2011-04-21 18:10:34

+0

好的,我想我明白了爲什麼發生這種情況 - 我會更新答案。 – Pointy 2011-04-21 18:16:25

+0

對於some_id你是對的,我還沒有機會清理它。感謝您的提醒。儘管第二批切換仍然沒有觸發。 – 2011-04-21 18:56:02

2

如果您在代碼中放置類似睡眠功能的文檔DOM,則不會更新您的文檔,它只會掛起瀏覽器。它只在腳本完成當前運行時更新。您必須使用setTimeout和異步操作並在回調函數中更新文檔。