jQuery的扩展有两种,全局(和java中类方法,类属性一样),对象。
- 全局函数的表现形式是:$.message()等
- 而对象扩展的形式是:$("#input2").add(1,2)等
首先呢我们建立一个jquery-extend-1.4.2.js的文件,表示将要扩展jquery1.4.2, 然后建立一个网页进行测试,网页中要导入jquery1.4.2和这个将要扩展的文件。
1,刚才说了,jQuery有两种扩展形式,我们先来看第一种:
//one:直接加 jQuery.bar = function(param) { alert('直接加方法bar,参数是 "' + param + '".'); }; //调用: $.bar('afei') //two:使用扩展 jQuery.extend({ foo1:function(){alert("加扩展方法 foo1");}, bar1:function(param){alert("加扩展方法 foo1bar1,参数 是"+param);} }); //调用 $.bar1("afei-1"); //three,使用命名空间 jQuery.afeiPlugin = { foo3:function() { alert('自定应命名空间,加方法foo3'); }, bar3:function(param) { alert('自定应命名空间,加方法bar3,参数是 "' + param + '".'); } }; //调用 $.afeiPlugin.bar3("我是阿飞"); //使用命名空间的这个其实蛮常用的,比如我们用的jquery.messager.js这个插件 //的这些方法 比如$.messager.show("我是消息")就是这样的。
2,对象级别的插件开发,代码如下
//形式1 (function($){ $.fn.extend({ test1:function(opt,callback){ alert(opt+" : "+callback); } }) })(jQuery); //形式2 (function($) { $.fn.test2 = function(opt,callback) { alert(opt+" : "+callback); }; })(jQuery); //调用 $("#input2").test2(3,4);
这个扩展的形参是$,最后在完成的时候传入jQuery对象,那么在插件里面也可以用$来操作query了。
上面两种扩展方式比较简单,可以完成基本的扩展 ,下面给出一个完整的例子。
// 创建一个闭包 (function($) { // 插件的定义 $.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); }); }; // 私有函数:debugging function debug($obj) { if (window.console && window.console.log) window.console.log('hilight selection count: ' + $obj.size()); }; // 定义暴露format函数 $.fn.hilight.format = function(txt) { return '<strong>' + txt + '</strong>'; }; // 插件的defaults $.fn.hilight.defaults = { foreground: 'red', background: 'yellow' }; // 闭包结束 })(jQuery);
总结一下:
1,jQuery为开发插件提拱了两个方法,分别是:
jQuery.fn.extend(object); 给jQuery对象添加方法。
jQuery.extend(object); 为扩展jQuery类本身.为类添加新的方法
2,其中jQuery.fn.extend(object)使我们编写插件功能时常用的。
比如我们要开发一个插件,做一个特殊的编辑框,当它被点击时,便alert 当前编辑框里的内容。可以这么做:
$.fn.extend({
alertValue:function(){
$(this).click(function(){
alert($(this).val());
});
}
});
然后$("test1").alertValue();这样,在点击进入时,可弹出表单元素的值。
下面带附件