jQuery插件的开发
jQuery插件的开发包括两种:
一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法。jQuery的全局函数就是属于jQuery命名空间的函数;另一种是对象级别的插件开发,即给jQuery对象添加方法。
本文提供的jQuery插件开发框架综合上述两种方式,代码如下所示:
// AMD support (function(factory) { //"use strict"; if (typeof define === 'function' && define.amd) { // using AMD; register as anon module define(['jquery'], factory); } else { // no AMD; invoke directly factory((typeof (jQuery) != 'undefined') ? jQuery : window.Zepto); } } (function($) { "use strict"; var pluginNS = 'InputBox', pluginPfx = 'IP', /* ---------------------------------------- VARS, CONSTANTS ---------------------------------------- */ totalInstances = 0, /* plugin instances amount */ /* ---------------------------------------- DEFAULT OPTIONS 默认参数 ---------------------------------------- */ defaults = { nParam: 0 }, /* ---------------------------------------- METHODS 公有函数 ---------------------------------------- */ methods = { init: function(options) { var opts = $.extend(true, {}, defaults, options); /* plugin constructor */ return $(this).each(function() { $this = $(this); if (!$this.data(pluginPfx)) { /* prevent multiple instantiations */ /* store options and create objects in jquery data */ $this.data(pluginPfx, { idx: ++totalInstances, /* instance index */ opt: opts /* options */ });
var d = $this.data(pluginPfx), o = d.opt; } }); }, destroy:function(){ } }, /* ---------------------------------------- FUNCTIONS 私有函数 ---------------------------------------- */ _default = function(opts) { }; /* ---------------------------------------- PLUGIN SETUP ---------------------------------------- */ /* plugin constructor functions */ /* usage: $(selector).pluginNS(); 对象级别*/ $.fn[pluginNS] = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === "object" || !method) { return methods.init.apply(this, arguments); } else { $.error("Method " + method + " does not exist!"); } }; /* usage: $.pluginNS(); 类级别*/ $[pluginNS] = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === "object" || !method) { return methods.init.apply(this, arguments); } else { $.error("Method " + method + " does not exist!"); } }; /* allow setting plugin default options. usage: $.pluginNS.defaults.nParam=5; to apply any changed default options on default selectors (below), use inside document ready fn */ $[pluginNS].defaults = defaults; }));
上述代码参考开源项目jQuery.mCustomScrollbar插件的整理。
......
分类:
前端开发
标签:
JavaScript
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期