jQuery 插件开发入门
jQuery插件开发包括三种:
1. 封装对象方法的插件
这种插件将对象方法封装起来,用于对通过选择器获取的jQuery对象进行操作,是最常见的一种插件,有两种形式可实现:
形式1:
1 (function(){ 2 $.fn.extend({ 4 pluginName:function(options,callback){ 6 } 7 }); 8 })(jQuery);
形式2:
1 (function($){ 2 $.fn.pluginName = function(){ 3 // plugin implement code 4 } 5 })(jQuery);
附注:1. 在插件内部,this指向的是当前通过选择器获取的jQuery对象,而不是Dom元素。
2. 可以通过this.each遍历所有jQuery对象集合中的DOM元素。
3. 插件应该返回一个jQuery对象,以保证插件的可链式操作,除非插件要返回一些要获取的量。
例如:编写一个改变DOM元素文本颜色的插件color();
1 (function(){ 2 $.fn.extend({ 3 "color":function(value){ 4 if(value==undefined){ 5 return this.css("color"); 6 }else{ 7 return this.css("color",value); 8 } 9 } 10 }); 11 })(jQuery);
2. 封装全局函数的插件:
此插件将独立的函数添加到jQuery的命名空间下,如jQuery.ajax(), jQuery.extend(),jQuery.each()等...
添加全局函数有三种方式:
形式1:直接在jQuery对象下扩展
1 jQuery.foo = function() { 2 alert('This is a test. This is only a test.'); 3 }; 4 jQuery.bar = function(param) { 5 alert('This function takes a parameter, which is "' + param + '".'); 6 }; 7 调用时和一个函数的一样的:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');
形式2:使用extend函数扩展jQuery方法
1 jQuery.extend({ 2 foo: function() { 3 alert('This is a test. This is only a test.'); 4 }, 5 bar: function(param) { 6 alert('This function takes a parameter, which is "' + param +'".'); 7 } 8 });
形式3:在命名空间下扩展方法
1 jQuery.myPlugin = { 2 foo:function() { 3 alert('This is a test. This is only a test.'); 4 }, 5 bar:function(param) { 6 alert('This function takes a parameter, which is "' + param + '".'); 7 } 8 }; 9 采用命名空间的函数仍然是全局函数,调用时采用的方法: 10 $.myPlugin.foo(); 11 $.myPlugin.bar('baz');
例如实现一个去掉字符串左右空格的插件:
1 (function(){ 2 $.extend({ 3 ltrim: function(str){ 4 return (str || "").replace(/^\s+/g,""); 5 }, 6 rtrim:function(str){ 7 return (str || "").replace(/\s+$/g,""); 8 } 9 }); 10 })(jQuery);
3. 扩展jQuery选择器插件
例如实现一个选取一定区间的元素选择器:between
1 (function($){ 2 $.extend(jQuery:expr[":"],{ 3 between: function(a,i,m){ 4 var tmp = m[3].split(","); 5 return tmp[0]-0 < i && tmp[1]-0>i 6 } 7 }); 8 })(jQuery); 9 10 //插件应用 11 $("div:between(2,5)").css("color","#f00");

浙公网安备 33010602011771号