jQuery官方给了一套对象级别开发插件的模板 。如果使用的是 sublimeText 编辑器,推荐安装插件 jQuery,在文件中输入 plugin + Enter 会自动生成代码片段。安装成功后在 js 文件中输入 plugin ,会出现下图所示内容: 选择 plugin (method basic),出现以下内容:(function($) {// What does the pluginName plugin do?$.fn.pluginName = function(options) { if (!this.length) { return this; } var opts = $.extend(true, {}, $.fn.pluginName.defaults, options); this.each(function() { var $this = $(this); }); return this;};// default options$.fn.pluginName.defaults = { defaultOne: true, defaultTwo: false, defaultThree: ‘yay!’};})(jQuery);给插件起个名字,添加到红框内 ,在绿框内设置所需的参数,在蓝框内编写插件的主方法。 在 HTML 中调用该插件:引入 jQuery 和插件 js 文件,选择 DOM 元素,调用插件。可以参考下面这个封装插件的实例:<!DOCTYPE html><html lang=“en”><head> <meta charset=“UTF-8”> <title>jQplugin</title></head><body> <div class=“box”> <input type=“button” class=“btn1” value=“btn1”> <input type=“button” class=“btn2” value=“btn2”> </div></body><script src=“https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><script>// 插件封装(function($) { // What does the pluginName plugin do? $.fn.pluginName = function(options) { if (!this.length) { return this; } var opts = $.extend(true, {}, $.fn.pluginName.defaults, options); this.each(function() { var $this = $(this); $(opts.btn1).click(function(event) { alert($(this).val()); }); $(opts.btn2).click(function(event) { alert($(this).val()); }); }); return this; }; // default options $.fn.pluginName.defaults = { btn1: null, btn2: null };})(jQuery);// 调用插件$(function() { $(".box”).pluginName({ btn1: “.btn1”, btn2: “.btn2” })});</script></html>期待您的关注!