首页 > 语言 > JavaScript > 正文

jQuery插件开发汇总

2024-05-06 14:58:20
字体:
来源:转载
供稿:网友

一、jQuery插件开发两个底层方法
jQuery.extend([deep ], target [, object1 ] [, objectN ] )
将两个或更多对象的内容合并到第一个对象。

1、deep 如果是true,合并成为递归(又叫做深拷贝)
2、target 一个对象,如果附加的对象被传递给这个方法将那么它将接收新的属性,如果它是唯一的参数则将扩展jQuery的命名空间,这对于插件开发者希望向 jQuery 中添加新函数时是很有用的。
3、object1 一个对象,它包含额外的属性合并到第一个参数
4、包含额外的属性合并到第一个参数
当我们提供两个或多个对象给/(.extend(),对象的所有属性都添加到目标对象(target参数) 目标对象(第一个参数)将被修改,并且将通过/).extend()返回。然而,如果我们想保留原对象,我们可以通过传递一个空对象作为目标对象:
var settings = $.extend({}, defaults, options);
在默认情况下,通过$.extend()合并操作是不递归的;

var object1 = {apple: 0,banana: {weight: 52, price: 100},cherry: 97};var object2 = {banana: {price: 200},durian: 100};$.extend(object1, object2);//{apple: 0, banana: {price:200}, cherry: 97, durian: 100}$.extend(true, object1, object2);//{apple: 0, banana: {weight: 52, price:200}, cherry: 97, durian: 100}jQuery.fn.extend()

在jQuery源码中有jQuery.fn = jQuery.prototype = function(){……}即指向jQuery对象的原型链,对其它进行的扩展,作用在jQuery对象上面;

总结

1、jQuery.extend()能够创建全局函数或选择器,在实际开发中常使用jQuery.extend()方法作为插件方法传递系列选项结构的参数
2、jQuery.fn.extend()能够创建jQuery对象方法,一般用此方法来扩展jQuery的对象插件
二、jQuery插件开发通用框架

;(function($, window, document, undefined){ //Plugin code here})(jQuery, window, document);

使用分号是为了防止因前面的代码没有使用分号而导致插件函数不能正确解析
传入jQuery是为了确保在匿名函数中正确的使用jQuery对象,防止多库共存时$冲突
传入window、document并非必须,只不过为了更快的访问window和document
传入undefined是为了防止undefined变量被更改,确保undefined的准确性

三、jQuery插件开发的3种形式
1、类级别开发(封装全局函数的插件)
类级别写法:

//方式1;(function($, window, document, undefined){ $.pluginName = function(){  //Plugin implementation code here }; })(jQuery, window, document);//方式2 当全局函数较多时;(function($, window, document, undefined){ $.extend({  pluginName = function(){   //Plugin code here  };  })})(jQuery, window, document);

调用方法:$.pluginName();

2、对象级别的插件开发
对象级别插件写法:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选