jQuery - 外掛



外掛是一段用標準 JavaScript 檔案編寫的程式碼。這些檔案提供了有用的 jQuery 方法,可以與 jQuery 庫方法一起使用。

有很多 jQuery 外掛可用,您可以從 https://jquery.com/plugins 的儲存庫連結下載。

如何使用外掛

為了使外掛的方法對我們可用,我們在文件的 <head> 中包含外掛檔案,這與 jQuery 庫檔案非常相似。

我們必須確保它出現在主 jQuery 原始檔之後,以及我們自定義 JavaScript 程式碼之前。

以下示例顯示瞭如何包含 jquery.plug-in.js 外掛 -

<html>
   <head>
      <title>The jQuery Example</title>
		
      <script type = "text/javascript" 
         src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>

      <script src = "jquery.plug-in.js" type = "text/javascript"></script>
      <script src = "custom.js" type = "text/javascript"></script>
      
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            .......your custom code.....
         });
      </script>
   </head>
	
   <body>
      .............................
   </body>
</html>

如何開發外掛

編寫自己的外掛非常簡單。以下是建立方法的語法 -

jQuery.fn.methodName = methodDefinition;

這裡 methodNameM 是新方法的名稱,而 methodDefinition 是實際的方法定義。

jQuery 團隊推薦的指南如下 -

  • 您附加的任何方法或函式都必須在末尾帶分號 (;)。

  • 您的方法必須返回 jQuery 物件,除非明確說明了其他情況。

  • 您應該使用 this.each 來迭代當前匹配元素的集合 - 透過這種方式可以生成簡潔且相容的程式碼。

  • 以 jquery 為檔名字首,然後是外掛名稱,最後以 .js 結尾。

  • 始終將外掛直接附加到 jQuery 而不是 $,以便使用者可以透過 noConflict() 方法使用自定義別名。

例如,如果我們編寫一個名為 debug 的外掛,則此外掛的 JavaScript 檔名為 -

jquery.debug.js

使用 jquery. 字首消除了與旨在與其他庫一起使用的檔案發生任何可能的名稱衝突。

示例

以下是一個用於除錯目的的小型外掛,具有警告方法。將此程式碼儲存在 jquery.debug.js 檔案中 -

jQuery.fn.warning = function() {
   return this.each(function() {
      alert('Tag Name:"' + $(this).prop("tagName") + '".');
   });
};

以下示例顯示了 warning() 方法的使用。假設我們將 jquery.debug.js 檔案放在 html 頁面的同一目錄中。

<html>
   <head>
      <title>The jQuery Example</title>
		
      <script type = "text/javascript" 
         src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
		
      <script src = "jquery.debug.js" type = "text/javascript">
      </script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").warning();
            $("p").warning();
         });
      </script>	
   </head>
	
   <body>
      <p>This is paragraph</p>
      <div>This is division</div>
   </body>
</html>

這將向您發出以下結果的警報 -

This is paragraph
This is division
廣告