文章参考 http://www.cnblogs.com/ellisonDon/archive/2012/08/12/2635316.html
API 说明
1、在元素上存放数据,返回jQuery对象。
2、如果jQuery集合指向多个元素,那将在所有元素上设置对应数据。
使用例子
$("div").data("blah"); // undefined $("div").data("blah", "hello"); // blah设置为hello $("div").data("blah"); // hello $("div").data("blah", 86); // 设置为86 $("div").data("blah"); // 86 $("div").removeData("blah"); //移除blah $("div").data("blah"); // undefined $("div").data("test", { first: 16, last: "pizza!" }); $("div").data("test").first //16; $("div").data("test").last //pizza!; jQuery.data(document.body, 'foo', 52); jQuery.data(document.body, 'bar', 'test');
模拟jquery的data()缓存数据方法
$ = function() { var expando = "jQuery" + ("1.6" + Math.random()).replace(/\D/g, ''); function getData(cache, name) { return cache[name]; } function setData(cache, name, value) { cache[name] = value; } function getCache(obj) { obj[expando] = obj[expando] || {}; return obj[expando]; } return { data : function(obj, name, value) { var cache = getCache(obj); if (value === undefined) { return getData(cache, name); } else { setData(cache, name, value); } } } }();
为对象附加数据
obj = {}; $.data(obj, {name1: 'value1', name2: 'value2'}); document.write("$.data(obj, 'name1') = " + $.data(obj, 'name1') + '<br />' ); document.write("$.data(obj, 'name2') = " + $.data(obj, 'name2') + '<br />'); for (var key in obj) { document.write("obj." + key + '.name1 = ' + obj[key].name1 + '<br />'); document.write("obj." + key + '.name2 = ' + obj[key].name2); }
为 DOM Element 附加数据
window.onload = function() { div = document.getElementById('div_test'); $.data(div, 'name', 'value'); document.write($.data(div, 'name')); }
在控件中定义data属性,获取属性数据的方法
<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}' id="huangbiao"></div> <script> $(function(){ // $("div").data("role") === "page"; // $("div").data("lastValue") === 43; // $("div").data("hidden") === true; // $("div").data("options").name === "John"; console.log($("#huangbiao").data("role")); console.log($("#huangbiao").data("lastValue")); console.log($("#huangbiao").data("hidden")); console.log($("#huangbiao").data("options").name); }); </script>