如何建立一個自定義 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-06-12

500 瀏覽量

助你職業起步生涯

完成課程認證

入門
廣告
© . All rights reserved.