jQuery 为开发插件提拱了两个方法,分别是:
jQuery.extend(object); 为jQuery类添加添加类方法,可以理解为添加静态方法。如:
$.extend({
add:function(a,b){
return
a+b;}
});
便为jQuery添加一个为add的"静态方法",之后便可以在引入jQuery的地方,使用这个方法了,
$.add(3,4); //return 7
jQuery.fn.extend(object); 对jQuery.prototype进得扩展,就是为jQuery类添加"成员函数"。jQuery类的实例可以使用这个"成员函数"。
比如我们要开发一个插件,做一个特殊的编辑框,当它被点击时,便alert 当前编辑框里的内容。可以这么做:
$.fn.extend({
alertWhileClick:function(){
$(
this
).click(function(){
alert($(
this
).val());
});
}
});
$(
"#input1"
).alertWhileClick();
//页面上为:<input
id="input1" type="text"/>
$("#input1") 为一个jQuery实例,当它调用成员方法 alertWhileClick后,便实现了扩展,每次被点击时它会先弹出目前编辑里的内容。
注: 根据jQuery的官方说明,插件的开发最好是写在
(function($){
//code
})(jQuery);
里面,否则的话有可能引起冲突。