---
title: "jQuery插件开发学习"
author: "zhoucl"
date: "2011-11-07T16:17:52Z"
tags: []
categories: ["Web前端"]
slug: "jquery"
draft: false
lastmod: "2011-11-08T16:53:12Z"
id: 1239737
url: "https://zhoucl.iteye.com/blog/1239737"
---

使用jQuery来做前端实有一段时间了，确实也感觉到jQuery的强大和书写相对简单了，不过一直也没去研究过相关的源码，以后有机会还是值得去看看jQuery方面源吗，这段时间对js接触的较多，使用了各种jQuery相关的插件，比如jquery.ui.datepicker.js，flexigrid.js等，确实给开发工作带来了较大的方便，今天自己也依葫芦画瓢，理解了一下jQuery对于插件方面的知识。

 

**1、jQuery插件编写准备**

要使用jQuery进行自定义插件的编写，首先应该的是了解jQuery的插件机制或者说是通过jQuery库本身提供的哪些函数进行插件的编写，主要涉及的两个函数是：jQuery.extend(object)和jQuery.fn.extend(object)，其具体作用可以通过查找jQuery的[API文档](http://docs.jquery.com/) 得到，这里也把API简单转过来：

**A、 jQuery.extend(object)**

扩展jQuery对象本身，用来在jQuery命名空间上增加新函数。

例如：

```
jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
}); 
```

使用方法：

```
jQuery.min(2,3);  //=> 2
$.max(4,5);         //=>5
```

**B、jQuery.fn.extend(object)**

扩展 jQuery 元素集来提供新的方法（通常用来制作插件）。具体实例将在下面进行一个简单的示例来进行了解。

 

2、简单的jQuery插件的编写

A、jQuery插件的基本格式

```
/*
 * digitClocker
 * @author: zhoucl
 * @date  : 08/11/2011
 */
(function($, undefined){	
      ...
      //code here
      ...
})(jQuery);

```

B、将原来直接javascript编写的一个电子时钟改写为jQuery插件使用，代码如下：

```
/*
 * digitClocker
 * @author: zhoucl
 * @date  : 03/11/2011
 */
(function($, undefined){	
	$.extend($.fn, {
		digitclocker: function(settings){
			var params = $.extend({
				baseURL: '../js/jquery/custom_plugins/',
				imgPath: 'digits/'
			}, settings);
			
			for(var i = 1; i < 9; i++) {
				if(i % 3 == 0) $(this).append("<img alt='0' src='" + params.baseURL + params.imgPath + "colon.gif'>");
				else $(this).append("<img class='clockImage' alt='0' src='" + params.baseURL + params.imgPath + "0.gif'>");
			}
			
			new DigitClock(params, $(this));
		}
	});
	
	setInterval(function(){
		DigitClock.reDraw();
	}, 1000);
	
	DigitClock = function(params, container) {
		this.params = params;
		this.container = container;
		
		DigitClock.clocks.push(this);
		DigitClock.reDraw();
	}
	
	DigitClock.clocks=[];
	
	DigitClock.reDraw = function() {
		var d=new Date();
		for (var i = 0; i < this.clocks.length; i++) {
			this.clocks[i].setTime(d.getHours(),d.getMinutes(),d.getSeconds());
		}
	}
	
	DigitClock.preZero = function(n, pos) {
		return ("0"._digitClockRepeat(pos-1)+n).slice(-pos);
	}
	
	DigitClock.prototype = {
		setTime : function(h, i ,s) {
			this.setImage(
				DigitClock.preZero(h,2) + DigitClock.preZero(i,2) + DigitClock.preZero(s,2)
			)
		},
		
		setImage: function(s) {
			s = s.split("");
			var baseURL = this.params.baseURL;
			var imgPath = this.params.imgPath;
			var i = 0;
			$(".clockImage", this.container).each(function(){
				$(this).attr("src", baseURL + imgPath + s[i++] +".gif");
			});
		}
	}
	
	String.prototype._digitClockRepeat = function(n) {
		return new Array(n+1).join(this);
	}
})(jQuery);
```

 引用上述js文件，在页面中得调用代码如下：

```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>simple_test.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <!--调用jQuery的库：jquery-1.5.2.js-->
    <script src="../js/jquery/jquery-1.5.2.js" type="text/javascript"></script>
    <script src="../js/jquery/custom_plugins/jquery.clzps.digitclock.js" type="text/javascript"></script>
    <script>
      $(function(){
          $('#digitClock').digitclocker({
		baseURL: '../js/jquery/custom_plugins/',
		imgPath: 'digits/'
	  });
      });
    </script>
  </head>
  
  <body>
     <div id="digitClock"></div>
  </body>
</html>
```

效果图如下：  
![](http://dl.iteye.com/upload/attachment/584668/212717e0-c347-306d-b364-dbaac7c29cad.jpg)

至此，一个简单的jQuery插件编写完成！~~本节源码也可访问放在[google开源](http://code.google.com/p/some-jquery-plugins/downloads/list) 链接