2017-07-24 更新:增加单例模式。
jquery插件开发框架代码:
/** 插件编写说明:* 1、插件命名:jquery.[插件名].js,如jquery.plugin.js* 2、对象方法添加到jQuery.fn上,全局方法添加到jQuery对象本身上* 3、插件内部的this指向通过选择器获取的jQuery对象* 4、可以使用this.each遍历所有的元素* 5、所有的方法以分号结束;插件头部先添加一个分号* 6、插件应该返回一个jQuery对象,以保证插件的链式操作* 7、使用闭包形式,使用$作为jQuery的别名以避免冲突* 8、单例模式*///为了兼容性良好,开始前有个分号;//传入jQuery是为了确保在匿名函数中正确的使用jQuery对象,防止多库共存时$冲突//传入window、document并非必须,只不过为了更快的访问window和document//获得没有未被修改的 \'undefined\',因为实际并没有传递这个参数。(function($, win, doc, undefined) {var alertPlugin = function(opts) {//保存this变量var _self = this;//定义默认参数_self.opts = {content: \'弹出内容\'};//根据传入的参数扩展默认参数if(opts && $.isPlainObject(opts)) {$.extend(_self.opts, opts);}//调用函数方法_self.show(_self.opts);};//函数方法实现alertPlugin.prototype = {show: function(opts) {alert(opts.content);}}//扩展插件$.fn.extend({alertPlugin: function(opts) {//遍历所有元素return this.each(function() {//单例模式var me = $(this),instance = me.data(\'alertPlugin\');if(!instance) {instance = new alertPlugin(opts);me.data(\'alertPlugin\', instance)}});}});})(jQuery, window, document); //jQuery,window,document作为实参
插件调用:
//未传递参数的调用$(\'.a\').alertPlugin();//传递参数的调用$(\'.a\').alertPlugin({content: \'新弹出内容\'});
转载于:JQuery/3687257