---
title: "读jq之六（数据暂存）"
author: "zhouyrt"
date: "2010-03-19T16:52:38Z"
tags: []
categories: ["Web前端"]
slug: "jq"
draft: false
lastmod: "2010-12-03T16:57:16Z"
id: 619969
url: "https://snandy.iteye.com/blog/619969"
---

jq的$.data，$.removeData方法设计的很巧妙，为增强理解模仿其写了个。都三个方法set，get，remove都挂在data对象上。

 

```
(function (){

	var stamp = '$' + (new Date).getTime(), uid = 0, cache = {};

	var data = {

		set : function(el, name, data) {

			var id = el[ stamp ], thisCache;

			if (!id) {
				id = ++uid;
			}

			if ( !cache[ id ] ) {
				el[ stamp ] = id;
				cache[ id ] = {};
			}

			thisCache = cache[ id ];

			if ( data !== undefined ) {
				thisCache[ name ] = data;
			}
			
		},

		get : function(el, name) {

			var id = el[ stamp ], thisCache = cache[ id ];
			return typeof name === "string" ? thisCache[ name ] : thisCache;

		},
		
		remove : function(el, name) {
			var id = el[ stamp ], thisCache = cache[ id ];
			if ( name ) {
				if ( thisCache ) {
					delete thisCache[ name ];
				}
			} else {
				try{
					delete el[ stamp ];
				}catch(e){
					el.removeAttribute( stamp );
				}
				delete cache[ id ];
			}		
		}

		
	};
	
	window.data = data;

})();
```