jQuery插件(一)
一、jQuery插件编写方法与形式
编写jQuery插件的目的是为了重用,jQuery为我们提供了两种插件编写的方式:
1 jQuery.fn.extend(object),为jQuery对象添加方法,使用时如$(“#id”).method()
2 jQuery.extend(object),为jQuery类添加方法,使用时如$.ajax
第一种:为jQuery对象添加方法
jQuery.fn.debug = function() {
return this.each(function(){alert(this);
});
};
第二种:为jQuery类添加静态方法
if(window.console) {
console.debug(message);
} else {
alert(message);
}
};
二、编写时需注意的事项
1、编写静态方法时最好给出名字空间,避免带来问题
jQuery.log = {
error : function() { ... },
warning : function() { ... },
debug : function() { ... }
};
插件将以以下形式使用:$.log.debug()
三、代码示例
(function($) {
$.fn.myPlugin = function(settings) {
var config = {'foo': 'bar'};
if (settings) $.extend(config, settings);
this.each(function() {
// element-specific code here
});
return this;
};
})(jQuery);