15.插件化

15.1  jQuery的插件的一般写法

 1         (function ($) {
 2             //扩展这个方法到jQuery
 3             $.fn.extend({
 4                 //插件名字
 5                 pluginname: function () {
 6                     return this.each(function () {
 7                         //在这里编写相应代码进行处理
 8                     });
 9                 }
10             })
11             //传递jQuery到内层作用域去,如果window,document在里面用得多,也可在这里传入
12         })(jQuery);

 1         (function ($) {//这个东西叫IIFE
 2             //扩展这个方法到jQuery
 3             var Plugin = function () {
 4 
 5             }
 6             Plugin.prototype = {};
 7             $.fn.extend({
 8                 //插件名字
 9                 pluginname: function (options) {//用户的统一配置对象或方法名
10                     //遍历匹配元素的集合
11                     var args = [].slice.call(arguments, 1);
12                     return this.each(function () {
13                         //在这里编写相应代码进行处理
14                         var ui = $._data(this, pluginname);
15                         if (!ui) {
16                             var opts = $.extend(true, {}, $.fn.pluginname.defaults, typeof options === "object" ? options : {});
17                             ui = new Plugin(opts, this);
18                             $._data(this, pluginnanem, ui);
19                         }
20                         if (typeof options === "string" && typeof ui[options] === "function") {
21                             ui[options].apply(ui, args);//执行插件的方法
22                         }
23                     });
24                 }
25             });
26             $.fn.pluginname.defaults = {/**/ }//默认配置对象
27             //传递jQuery到内层作用域去,如果window,document在里面用得多,也可在这里传入
28         })(jQuery);

原文地址:https://www.cnblogs.com/wingzw/p/7365183.html