jQuery - 方法鏈



在討論jQuery 方法鏈之前,考慮一下當您想要對 HTML 元素執行以下操作時的情況:

  • 1 - 選擇一個段落元素。

  • 2 - 更改段落的顏色。

  • 3 - 對段落應用淡出效果。

  • 4 - 對段落應用淡入效果。

以下是執行上述操作的 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() {
      $("button").click(function(){
         $("p").css("color", "#fb7c7c");
         $("p").fadeOut(1000);
         $("p").fadeIn(1000);
      });
   });
</script>
<style>
   button{width:100px;cursor:pointer;}
</style>
</head>
<body>
   <p>Click the below button to see the result:</p>

   <button>Click Me</button>
</body>
</html>

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() {
      $("button").click(function(){
         $("p").css("color", "#fb7c7c").fadeOut(1000).fadeIn(1000);
      });
   });
</script>
<style>
   button{width:100px;cursor:pointer;}
</style>
</head>
<body>
   <p>Click the below button to see the result:</p>

   <button>Click Me</button>
</body>
</html>

帶鏈式呼叫的動畫

在編寫 jQuery 動畫程式時,我們可以利用 jQuery 方法鏈。以下是使用鏈式呼叫的簡單動畫程式:

<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $("div").animate({left: '250px'})
         .animate({top: '100px'})
         .animate({left: '0px'})
         .animate({top: '0px'});
      });
   });
</script>
<style>
   button {width:125px;cursor:pointer}
   #box{position:relative;margin:3px;padding:10px;height:20px; width:100px;background-color:#9c9cff;}
</style>
</head>
<body>
<p>Click on Start Animation button to see the result:</p>

<div id="box">This is Box</div>
<button>Start Animation</button>
</body>
</html>
廣告