// 为元素保存数据
jQuery.data = function (elem, name, data) { // #1001
// 取得元素保存数据的键值
var id = elem[expando], cache = jQuery.cache, thisCache;
// 没有 id 的情况下,无法取值
if (!id && typeof name === "string" && data === undefined) {
return null;
}
// Compute a unique ID for the element
// 为元素计算一个唯一的键值
if (!id) {
id = ++uuid;
}
// 如果没有保存过
if (!cache[id]) {
elem[expando] = id; // 在元素上保存键值
cache[id] = {}; // 在 cache 上创建一个对象保存元素对应的值
}
// 取得此元素的数据对象
thisCache = cache[id];
// Prevent overriding the named cache with undefined values
// 保存值
if (data !== undefined) {
thisCache[name] = data;
}
// 返回对应的值
return typeof name === "string" ? thisCache[name] : thisCache;
}
// 删除保存的数据
jQuery.removeData = function (elem, name) { // #1042
var id = elem[expando], cache = jQuery.cache, thisCache = cache[id];
// If we want to remove a specific section of the element's data
if (name) {
if (thisCache) {
// Remove the section of cache data
delete thisCache[name];
// If we've removed all the data, remove the element's cache
if (jQuery.isEmptyObject(thisCache)) {
jQuery.removeData(elem);
}
}
// Otherwise, we want to remove all of the element's data
} else {
delete elem[jQuery.expando];
// Completely remove the data cache
delete cache[id];
}
}
// 检查对象是否是空的
jQuery.isEmptyObject = function (obj) {
// 遍历元素的属性,只有要属性就返回假,否则返回真
for (var name in obj) {
return false;
}
return true;
}
// 检查是否是一个函数
jQuery.isFunction = function (obj) {
var s = toString.call(obj);
return toString.call(obj) === "[object Function]";
}
下面的脚本可以保存或者读取对象的扩展数据。
代码如下:
// 数据操作
$("#msg").data("name", "Hello, world.");
alert($("#msg").data("name"));
$("#msg").removeData("name");
alert($("#msg").data("name"));