有时候,你的代码中需要一块功能的支持,比如, 你希望用一个方法将对 jQuery 对象的一长串操作封装起来, 那么,你会需要一个自己编写的插件。
大部分插件都是简单地在 $.fn 名字空间下添加方法。
jQuery 确保了在调用的方法内部 this 所指向的就是调用该方法的 jQuery 对象。
反过来,你的插件也应该确保返回同一的对象,除非是在文档里明确声明了。
下面是一个简单插件的例子:
Example 8.1. 这个插件用于 hover(鼠标划过)时添加/删除一个 class
// 插件定义
(function($){
$.fn.hoverClass = function(c) {
return this.hover(
function() { $(this).toggleClass(c); }
);
};
}(jQuery);
// 插件使用样例
$('li').hoverClass('hover');
想要了解更多插件开发的内容,可以阅读 Mike Alsup 撰写的 A
Plugin Development Pattern。文中讲述了他开发的一个叫 $.fn.hilight 的插件,
用于对在有 metadata 插件时提供一些支持,和一个统一设置插件的全局和实例参数的方法。
Example 8.2. Mike Alsup 的 jQuery 插件设计模式
//
// create closure
//
(function($) {
//
// plugin definition
//
$.fn.hilight = function(options) {
debug(this);
// build main options before element iteration
var opts = $.extend({}, $.fn.hilight.defaults, options);
// iterate and reformat each matched element
return this.each(function() {
$this = $(this);
// build element specific options
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
// update element styles
$this.css({
backgroundColor: o.background,
color: o.foreground
});
var markup = $this.html();
// call our format function
markup = $.fn.hilight.format(markup);
$this.html(markup);
});
};
//
// private function for debugging
//
function debug($obj) {
if (window.console && window.console.log)
window.console.log('hilight selection count: ' + $obj.size());
};
//
// define and expose our format function
//
$.fn.hilight.format = function(txt) {
return '<strong>' + txt + '</strong>';
};
//
// plugin defaults
//
$.fn.hilight.defaults = {
foreground: 'red',
background: 'yellow'
};
//
// end of closure
//
})(jQuery);
Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.