jQuery插件有两种写法
- $.extend(myMethod:function(){}) 类似于给jQuery添加静态方法
- $.fn.myMethod=function(){} 应用于DOM元素上的方法,一般jQuery都是使用这个方法
本文介绍$.fn.myMethod=function(){}这种方式
直接上一个例子,这个例子是对页面上所有的超链接应用样式
; (function ($, window, document, undefined) {$.fn.beautifulHyperlink = function (options) {var defaults = { 'color': 'red', 'fontSize': '15px' };var settings = $.extend({}, defaults, options);return this.each(function () {$(this).css({ 'color': settings.color, 'fontSize': settings.fontSize });});//this.css({ 'color': settings.color, 'fontSize': settings.fontSize });}})(jQuery, window, document)//调用方法$(function () {$('a').beautifulHyperlink({ 'color': 'yellow' });});
关键点如下
- 插件最前面添加
;
,作用是防止其他js代码结束没有;
,导致js错误 - 关于插件参数:options是用于传入的,defaults是默认值,settings是合并后最终参数值;$.extend({}, defaults, options)中的
{}
作用是保证default不被改变,饭后后续用到defaults中的原始值 - return的作用是保证链式编程
- this.each的作用是可以对每个dom元素单独处理,这里的例子可以不用this.each
- (function ($, window, document, undefined)和(jQuery, window, document)的作用是防止变量污染,保证插件中使用的局部变量;值的注意的是undefined没有传值进去,恰恰刚好传进去的undefined就是undefined,这是一个巧合
最后贴一下终极优化方案,使用面向对象的思想,把操作方法提到对象中
; (function ($, window, document, undefined) {var Beautifier = function (eles, opts) {this.$elements = eles;this.options = opts;this.defaults = { 'color': 'red', 'fontSize': '15px' };this.settings = $.extend({}, this.defaults, this.options);}Beautifier.prototype = {beautify: function () {var thisObj = this; //指向当前对象Beautifier,否则下面settings引用不到,因为each中的this是被遍历对象中当前值的dom对象return this.$elements.each(function () {$(this).css({ 'color': thisObj.settings.color, 'fontSize': thisObj.settings.fontSize });});//return this.$elements.css({ 'color': this.settings.color, 'fontSize': this.settings.fontSize });}};$.fn.beautifulHyperlinkEx = function (options) {var beautifier = new Beautifier(this, options);beautifier.beautify();}})(jQuery, window, document)
; (function ($, window, document, undefined) {var Beautifier = {beautify: function ($ele, settings) {$ele.css({ 'color': settings.color, 'fontSize': settings.fontSize });}};$.fn.beautifulHyperlink = function (options) {var defaults = { 'color': 'red', 'fontSize': '15px' };var settings = $.extend({}, defaults, options);return this.each(function () {Beautifier.beautify($(this), settings);});}})(jQuery, window, document)