您的位置:首页 > Web前端 > JQuery

如何编写jquery插件

2014-04-24 14:59 344 查看
jQuery插件的开发包括两种:

种类级别插件开发即给jQuery添加新全局函数相当于给jQuery类本身添加方法jQuery全局函数属于jQuery命名空间函数另种对象级别插件开发即给jQuery对象添加方法下面两种函数开发做详细说明

1、类级别插件开发

类级别插件开发直接理解给jQuery类添加类方法理解添加静态方法典型例子$.AJAX()函数函数定义于jQuery命名空间关于类级别插件开发采用下几种形式进行扩展:

1.1

添加新全局函数

添加一个全局函数我们只需下定义:

jQuery.foo =

function() { 

  alert('This is a test. This is only a

test.');

 };   

1.2

增加多全局函数

添加多全局函数采用下定义:

Java代码  收藏代码

jQuery.foo = function() { 

    alert('This is a test. This is

only a test.');

 };

jQuery.bar =

function(param) { 

   alert('This function takes a

parameter, which is "' + param + '".');

 }; 

调用时和函数样:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');

1.3

使用jQuery.extend(object); 

jQuery.extend({    

 foo:

function() {    

    alert('This is a test. This is

only a test.');    

 

},    

 bar: function(param)

{    

    alert('This function takes a

parameter, which is "' + param +'".');    

 

}   

 });

1.4

使用命名空间

虽jQuery命名空间我们禁止使用了大量javaScript函数名和变量名仍避免某些函数或变量名于其jQuery插件冲突因此我们习惯些方法封装另自定义命名空间

jQuery.myPlugin =

{        

 foo:function()

{        

  

alert('This is a test. This is only a

test.');         

 

},        

 

bar:function(param)

{        

  

alert('This function takes a parameter, which is "' + param +

'".');  

 

}       

 };

采用命名空间函数仍全局函数调用时采用方法:

$.myPlugin.foo();       

$.myPlugin.bar('baz');

通过技巧(使用独立插件名)我们避免命名空间内函数冲突

2、对象级别插件开发

对象级别插件开发需要下两种形式:、

形式1:

(function($){   

  

$.fn.extend({   

   

pluginName:function(opt,callback){   

             

// Our plugin implementation code goes

here.     

   

}   

   })   

})(jQuery);  

形式2:

(function($)

{     

    $.fn.pluginName = function()

{   

        

// Our plugin implementation code goes here.   

   

};    

})(jQuery);    

上面定义了jQuery函数,形参$函数定义完成之,把jQuery实参传递进去.立即调用执行样好处,我们写jQuery插件时,也使用$别名,而会与prototype引起冲突.

2.1

JQuery名称空间下申明名字

单插件脚本脚本包含多插件或者互逆插件(例:

$.fn.doSomething() 和

$.fn.undoSomething())需要声明多函数名字通常当我们编写插件时力求仅使用名字来包含所有内容我们示例插件命名highlight  

$.fn.hilight

= function() {  

   // Our plugin implementation

code goes

here.  

 };  

我们插件通过样被调用:

$('#myDiv').hilight();   

我们需要分解我们实现代码多函数该办有多原因:设计上需要;样做更容易或更易读实现;而且样更符合面向对象真麻烦事把功能实现分解成多函数而增加多余命名空间出于认识和利用函数javascript基本类对象我们样做像其对象样函数被指定属性因此我们已经声明hilightjQuery属性对象任何其属性或者函数我们需要暴露出来都"hilight"

函数被声明属性稍继续

2.2

接受options参数控制插件行

让我们我们插件添加功能指定前景色和背景色功能我们也许会让选项像options对象传递给插件函数例: 

// plugin definition

$.fn.hilight =

function(options) {

  var defaults = {

    foreground:

'red',

    background:

'yellow'

  };

  //

Extend our default options with those provided.

  var

opts = $.extend(defaults, options);

  // Our

plugin implementation code goes here.

};

我们插件样被调用:

$('#myDiv').hilight({

 

foreground: 'blue'

});

2.3

暴露插件默认设置

我们应该对上面代码种改进暴露插件默认设置对于让插件使用者更容易用较少代码覆盖和修改插件接下来我们开始利用函数对象   

//

plugin definition

$.fn.hilight =

function(options) {

  // Extend our default options withthose

provided.

  // Note that the first arg to extend isan

empty object -

  // this is to keep from overriding our

"defaults" object.

  var opts = $.extend({},

$.fn.hilight.defaults, options);

  // Our

plugin implementation code goes here.

};

// plugin

defaults - added as a property on our plugin function

$.fn.hilight.defaults = {

 

foreground: 'red',

  background: 'yellow'

}; 

现使用者包含像样行们脚本里:

//只需要调用次且定要ready块调用

$.fn.hilight.defaults.foreground

=

'blue';

接下来我们像样使用插件方法结设置蓝色前景色:

$('#myDiv').hilight();

所见我们允许使用者写行代码插件默认前景色而且使用者仍需要时候有选择覆盖些新默认值:

//

覆盖插件缺省背景颜色

$.fn.hilight.defaults.foreground = 'blue';

// ...

//

使用新缺省设置调用插件

$('.hilightDiv').hilight();

// ...

//

通过传递配置参数给插件方法来覆盖缺省设置

$('#green').hilight({

  foreground:

'green'

});

 

 

注1:
1、jQuery.extend(object) 扩展jQuery对象本身  $.method() ,静态方法样
2、$.fn.extend() 扩展 jQuery 元素集来提供新方法(通常用来制作插件)  $("#xx").method() 对象方法
 3、jQuery插件基本上都用 $.fn.extend() 原因 般都某些dom对象执行方法
    而选择器扩展 jQuery本身  $ 所用 jQuery.extend

 
注2:

$.fn指jquery命名空间加上fn上方法及属性会对jquery实例每有效

扩展$.fn.abc()

样子:$("#div").abc();

通常使用extend方法扩展详细请看API.

$.fx指jquery特效

使用显示、滑动、淡入淡出、动画等

$.fx.off关闭动画其实直接显示结jqueryextend和fn.extendjQuery开发插件提拱了两方法分别: jQuery.fn.extend(object);jQuery.extend(object); jQuery.extend(object); 扩展jQuery类本身.类添加新方法jQuery.fn.extend(object);给jQuery对象添加方法 fn 东西呢查看jQuery代码难发现jQuery.fn = jQuery.prototype = { init: function( selector, context ) {//.... //......}; 原来jQuery.fn = jQuery.prototype.对prototype肯定会陌生啦 虽javascript 没有明确类概念用类来理解会更方便jQuery便封装得非常好类比我们用 语句 $("#btn1") 会生成 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 当前编辑框里内容做:Java代码 $.fn.extend({ alertWh
4000
ileClick:function(){ $(this).click(function(){ alert($(this).val()); }); } }); $("#input1").alertWhileClick(); //页面上:<input id="input1" type="text"/>

$("#input1") jQuery实例当调用成员方法 alertWhileClick便实现了扩展每次被点击时会先弹出目前编辑里内容 真实开发过程当会做小白插件事实上jQuery提拱了丰富操作文档事件CSS ,Ajax、效方法结合些方法便开发出更加 Niubility 插件 jquery(function(){})与(function(){}(jQuery)区别1.first jQuery(function(){});全写jQuery(docunemt).ready(function(){});意义DOM加载完毕执行ready()方法2.(funtion(){}(jQuery);实际执行()(para)匿名方法只过传递了jQuery对象总结:jQuery(funtion(){});用于存放DOM对象代码执行其代码时DOM对象已经存用于存放开发插件代码

 

 

注2:

test要装成对象写:
<script>
var test=function(){
        var msgs = "testmsg";
        this.setMsgs=function(v){
               msgs=v;
        }
        this.getMsgs=function(){
               return msgs;
        }
}
var a=new test();
alert(a.getMsgs());//testmsg
a.setMsgs("123");
alert(a.getMsgs());//123
alert(a.msgs);//undefined,私有变量访问
</script>
jQuery扩展方法对象哦明白想要效种写法用时候变成$("选择器").test();方法对象

想了想非要写成对象也Javascript本身弱类型语言
<script>
(function ($) {
        $.fn.test = function () {
               var msgs = $(this).val();
               this.setMsgs=function(v){
                       msgs=v;
               }
               this.getMsgs=function(){
                       return msgs;
               }
               return this;//种写法相当于临时扩展了jQuery对象给加了两方法
        };
})(jQuery);
$(function(){
        alert($("#a").test().getMsgs());//testmsg2
})
</script>

<input type='text' id='a' value='testmsg2'/>

看懂上面没问题继续看懂别往下看了把上面先弄明白

把扩展代码换成
<script>
(function ($) {
        $.fn.test1 = function () {
               var msgs = $(this).val();//时候this指传进来jQuery对象
               var me=new Object();//声明了新对象哦时候msgs对象私有变量同处于test作用域下样也对
               me.msg2="属性";//才属性
               me.setMsgs=function(v){
                       msgs=v||msgs;
                       return this;//类似jQuery责任链把对象扔回去便下函数调用时候this已经jQuery对象了
               }
               me.getMsgs=function(){
                       return this.msg2+"|"+msgs;
               }
               return me;
        };
})(jQuery);
$(function(){
        alert($("#a").test1().getMsgs());//testmsg2
        alert($("#a").test1().setMsgs("224").getMsgs());
})
</script>

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: