如何編寫自定義 jQuery 外掛?
要建立 jQuery 外掛,首先建立一個名為 *jquery-demoplugin.js* 的檔案,其中包含以下程式碼。這是我們的外掛程式碼。此處,*demoplugin* 是我們外掛的名稱。你可以為自定義外掛新增任意名稱 −
(function ( $ ) { $.fn.demoplugin = function( options ) { var web = $.extend({ name: 'example' }, 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-demoplugin.js"></script> <script> $( document ).ready(function() { $( '#content ).demoplugin(); }); </script> </head> <body> <div id="content"></div> </body> </html>
廣告