如何建立自定義 jQuery 外掛?


若要建立 jQuery 外掛,首先建立名為 jquery-myplugin.js 的檔案,其中包含以下程式碼。這是我們的外掛程式碼。其中,myplugin 是我們外掛的名稱。

(function ( $ ) {
   $.fn.myplugin = function( options ) {
      var web = $.extend({
         name: 'tutorialspoint'
      }, options );
      return this.append('Website: ' + web.name + '.com');
   };
}( jQuery ));

現在,將其載入到 HTML 檔案 new.html:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="jquery-myplugin.js"></script>
<script>
$(document).ready(function() {
   $('#myclass').myplugin();
});
</script>
</head>
<body>
<div id="myclass"></div>
</body>
</html>

執行以上程式碼,你將看到可見的文字,顯示自定義外掛正常工作。

更新於: 2020 年 6 月 12 日

500 次觀看

開啟您的 職業

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.