> For the complete documentation index, see [llms.txt](https://docs.webmix.cc/jquery/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webmix.cc/jquery/8.-jquery-wai-gua-plugin.md).

# 8 簡易 jQuery 套件

## &#x20;套件規則

只要透過 **`$.fn`** 就可以寫一個基於 jquery 專用外掛。

先參考 IIFE(Immediately Invoked Function Expression) 範例：

```javascript
(function(a){
  alert(a);
})(5);
```

{% embed url="<https://codepen.io/carlos411/pen/wvKaWym>" %}

步驟一：在 IIFE 裡面寫

```javascript
(function(){
  // code here...
})();
```

步驟二：在 IIFE 裡代入 jQuery 參數，這是為了避免跟其它函式庫有命名上的衝突，jQuery 代入，由 **`$`** 變數承接：

```javascript
(function($){
  // code here...
})(jQuery);
```

步驟三：在 $.fn 繼續撰寫基於 jQuery 相關的自訂程式，並回傳 jQuery 物件

```javascript
(function($){

  $.fn.printMessage = function(params){
    // 其它原始碼...
    return this;
  };
  
})(jQuery);
```

## 自訂 printMessage 套件

將函式掛載在 jQuery 函式庫當中。

參考作法：

{% embed url="<https://codepen.io/carlos411/pen/ZEgQzpo>" %}
