简单模拟 jQuery data函数
通过给元素分配一个属性 data + 时间戳,确定是否有缓存,再根据 data 的全局 id 值 存储/获取 缓存的数据
html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <body> <div id="abc1"> aaa </div> <div id="abc2"> bbbb </div> <div id="abc3"> ccc </div> </body> </html>
javascript:
(function(){ var cache = {}, uuid = 0, timestamp = (new Date).getTime(); function appendData(elem, attrName, data){ var uid = elem[‘data‘+timestamp]; if(uid === undefined){ ++uuid; elem[‘data‘+timestamp] = uuid; cache[uuid] = {}; cache[uuid][attrName] = data; return data; }else{ return cache[uuid][attrName]; } } window.appendData = appendData; })(); window.onload = function(){ var e1 = document.getElementById(‘abc1‘); appendData(e1,‘opts‘, {a:"abc",b:"123"}); debugger; console.log(appendData(e1,‘opts‘)); };
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。