jQuery 学习笔记,七

七、扩展和自定义插件

1、为什么扩展?

a. 在整个站点范围内,维护代码的一致性

b. 由于JQuery的设计模式会给我们带来好处,所以应强制将我们的代码作为jQuery的扩展

c. 扩展jQuery可以利用现成的代码

2、jQuery插件的创作指导

a. 文件和函数的命名

给文件名加上前缀(jquery)

在加上插件的名字

以js扩展名结束

例如:jquery.fred.js

b. 小心‘$’

由于不知道使用jQuery的用户是否应用了 $.noConflict() 方法,所以不能直接使用$

根据前面介绍的方法,可以使用以下这个方式:

(function($){

//

// Plugin definition goes here

//

})(jQuery);

ok,现在已经解决了这个问题,然后呢……

c.把握复杂的参数列表

如果一个function含有两个参数,那么判断参数是否没有传入,是一件很容易的事情,我们可以

为没有传入的属性赋一个默认值,但是如果有很多参数,比如:

function complex(p1,p2,p3,p4,p5,p6,p7)

我们想要p2保持默认值,而传入p1,p7选项的话,就非常复杂了,需要按照下面的形式调用:

complex(valueA,null,null,null,null,null,valueB)

为了解决这个方法,可以把参数包装成一个JS对象,即

complex(valueA, {p7: valueB});

就可以轻松解决问题了

另外,为了更好的将选项传入function,可以用下面这个方法,更加好的实现,利用$.extend()

function complex(p1,options) {

var settings = $.extend({

option1: defaultValue1,

option2: defaultValue2,

option3: defaultValue3,

option4: defaultValue4,

option5: defaultValue5,

option6: defaultValue6

},options||{});

options||{}是为了避免options为空的情况

这样,默认值就会被options中的值覆盖,其余的将保持默认值

3、自定义实用方法

可以按照如下格式,去写实用function

(function($){

$.say = function(what) { alert('I say '+what); }

})(jQuery);

4、添加包装器方法

按照如下格式:

(function($){

$.fn.makeItBlue = function() {

return this.css('color','blue');

}

})(jQuery);

在这里, this代表的是包装集。如果使用this.each方法,那么在each方法中的this则代表DOM元素

一个例子:

(function($){

$.fn.setReadOnly = function(readonly) {

return this.filter('input:text')

.attr('readonly',readonly)

.css('opacity', readonly ? 0.5 : 1.0);

}

})(jQuery);

另一个例子

(function($){

var settings;

$.fn.photomatic = function(callerSettings) {

settings = $.extend({

photoElement: '#photomaticPhoto',

transformer: function(name) {

return name.replace(/thumbnail/,'photo');

},

nextControl: null,

previousControl: null,

firstControl: null,

lastControl: null

}, callerSettings || {});

settings.photoElement = $(settings.photoElement);

settings.thumbnails = this.filter('img');

settings.thumbnails.each(function(n){this.index = n;});

settings.current = 0;

settings.thumbnails.click(function(){ showPhoto(this.index); });

settings.photoElement.click(function(){

showPhoto((settings.current + 1) % settings.thumbnails.length);

});

$(settings.nextControl).click(function(){

showPhoto((settings.current + 1) % settings.thumbnails.length);

});

$(settings.previousControl).click(function(){

showPhoto((settings.thumbnails.length + settings.current - 1) %

settings.thumbnails.length);

});

$(settings.firstControl).click(function(){

showPhoto(0);

});

$(settings.lastControl).click(function(){

showPhoto(settings.thumbnails.length - 1);

});

showPhoto(0);

return this;

};

var showPhoto = function(index) {

settings.photoElement

.attr('src',

settings.transformer(settings.thumbnails[index].src));

settings.current = index;

};

})(jQuery);