jQuery - 回撥函式



一個jQuery 回撥函式是在當前效果完成後才會執行的函式。本教程將解釋什麼是jQuery 回撥函式以及為什麼要使用它們。

以下是任何 jQuery 效果方法的簡單語法

$(selector).effectName(speed, callback);

如果我們更詳細地瞭解一下,那麼 jQuery 回撥函式將如下編寫:

$(selector).effectName(speed, function(){
   <!-- function body -->
});

沒有回撥函式的示例

首先,讓我們來看一個不使用回撥函式的 jQuery 程式,在這裡,即使在隱藏效果完成之前,也會顯示警報訊息。

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").click(function(){
         $(this).hide(1000);
         alert("I'm hidden now");
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px; cursor:pointer}
</style>
</head>
<body>
   <p>Click on any of the squares to see the result:</p>

   <div>Hide Me</div>
   <div>Hide Me</div>
   <div>Hide Me</div>
</body>
</html>

jQuery 回撥函式

由於 Javascript(jQuery)程式碼執行的非同步特性,需要 jQuery 回撥函式。jQuery 效果可能需要一些時間才能完成,因此在效果仍在執行時,下一行程式碼可能會被執行。為了處理程式碼的非同步執行,jQuery 允許在所有效果方法中傳遞一個回撥函式,而此回撥函式的目的是僅在效果完成後執行。

示例

讓我們再次重寫上面的示例,這次我們使用一個在隱藏效果完成後執行的回撥函式。

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").click(function(){
         $(this).hide(1000, function(){
            alert("I'm hidden now");
         });
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px; cursor:pointer}
</style>
</head>
<body>
   <p>Click on any of the squares to see the result:</p>

   <div>Hide Me</div>
   <div>Hide Me</div>
   <div>Hide Me</div>
</body>
</html>

帶有動畫的回撥

jQuery animate() 方法也提供了使用回撥函式的機制。

示例

以下示例使用了一個在動畫效果完成後執行的回撥函式。

<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("#right").click(function(){
         $("div").animate({left: '250px'}, 1000, function(){
            alert("I have reached to the right");
         });
      });
      $("#left").click(function(){
         $("div").animate({left: '0px'}, 1000, function(){
            alert("I have reached to the left");
         });
      });
   });
</script>
<style>
   button{width:100px;cursor:pointer}
   #box{position:relative;margin:3px;padding:12px;height:100px; width:180px;background-color:#9c9cff;}
</style>
</head>
<body>
<p>Click on Left or Right button to see the result:</p>

<div id="box">This is Box</div>
<button id="right">Right Move</button>
<button id="left">Left Move</button>
</body>
</html>
廣告