•
编写
jQuery
插件
,
是从添加一个新的函数属性到
jQuery.fn
对象开始的,其中新的函数属性名为你要编写插件的名称:
•
jQuery.fn.myPlugin
= function() {
•
// Do your awesome
plugin
stuff here
•
};
<!--[if ppt]-->
•<!--[endif]-->
•
然而为了确保你的插件不会与其他可能使用
$
符号的
javascript
库冲突
,将
jQuery
对象当做参数传递到一个可立即执行的函数表达式中(
IIFE
),该函数表达式会通过
$
符号来映射
jQuery
对象,这样在该函数表达式内,
$
符号将不会被在其可执行的作用域中的其他库所覆盖。
•
(function( $ ) {
•
$.
fn.myPlugin
= function() {
•
// Do your awesome
plugin
stuff here };
})( jQuery );
•
编写一个实现了一些功能的插件。
•
(
function( $ ){
•
$.
fn.maxHeight
= function() {
•
var
max = 0;
•
this.each
(function() {
•
max = Math.max( max, $(this).height() );
•
});
•
return max;
•
};
•
})(
jQuery
);
•
•
var
tallest = $('div').
maxHeight
();
•
通过调用
.height()
来获取页面最高
div
元素的高度。
•
包含
可选项的复杂可定制化插件
,增加能
在被调用时可扩展
(
使用
$.
extend)
的默认设置
。避免
在调用插件时传递大量参数
,在
调用时使用一个需要覆盖掉的参数对象
。如下
•
(
function( $ ){
•
$.
fn.tooltip
= function( options ) {
•
var
settings = $.extend( {
•
'location' : 'top',
•
'background-color' : 'blue'
•
}, options);
•
return
this.each
(function() {
•
});
•
};
•
})(
jQuery
);
•
$('div').tooltip({ 'location' : 'left' });
•
当使用给定的可选项调用
tooltip
插件方法后,默认的
'
location'
属性会被设置成
'
left',
而
'
background-color'
属性则保持不变。
•
一
个单独的插件在
jQuery.fn
对象上的命名空间都不应超过一个
。
•
应该将所有插件的方法存放在一个对象字面量中,然后通过传递方法的字符串名称来调用。
•
(
function( $ ){
•
var
methods = {
•
init : function( options ) { // },
•
show : function( ) {// },
•
hide : function( ) { // },
•
update : function( content ) { // }
•
};
•
$.
fn.tooltip
= 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 on
jQuery.tooltip
' );
•
}
•
};
•
})(
jQuery
);
•
$('div').tooltip();
•
$('div').tooltip({
foo
: 'bar' });
•
$('div').tooltip('hide');
•
$('div').tooltip('update', 'This is the new tooltip content!');