8 簡易 jQuery 套件

套件規則

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

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

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

步驟一:在 IIFE 裡面寫

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

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

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

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

(function($){

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

自訂 externalLinkIcon 套件

自訂 .externalLinkIcon(),如果 <a> 標籤有 target="_blank" 的話,在標籤裡的最後面,加上一個 icon 做示意。

icon 路徑:

https://alldata.sgp1.digitaloceanspaces.com/images/external_link.png

提供 html:

<a href="https://tw.yahoo.com">yahoo 連結</a>
<br>
<a href="https://www.google.com" target="_blank">google 開新分頁連結</a>
<br>
<a href="https://www.pinterest.com/" target="_blank">pinterest開新分頁連結</a>

提供 css:

.icon_external{
  width: 12px;
  margin-left: 2px;
}

完成如下圖,有 target="_blank" 的連結,右邊多了小 icon:

參考作法:

Last updated