国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語言 > JavaScript > 正文

利用原生JS實(shí)現(xiàn)data方法示例代碼

2024-05-06 15:38:46
字體:
供稿:網(wǎng)友

前言

在開發(fā)中經(jīng)常會(huì)在DOM上存儲(chǔ)一些自定義數(shù)據(jù),我們可以通過setAttribute方法來實(shí)現(xiàn)。但是當(dāng)數(shù)據(jù)為引用類型時(shí),存儲(chǔ)后的數(shù)據(jù)卻無效。這里將用原生的JS對(duì)data方法進(jìn)行實(shí)現(xiàn)。

使用setAttribute:

<div id="test-data"></div><p class="test-data-list"></p><p class="test-data-list"></p><p class="test-data-list"></p><p class="test-data-list"></p>
var testData = document.querySeletor('#test-data');testData.setAttribute('baukh', {a:1,b:2})// 執(zhí)行后DOM節(jié)點(diǎn)變化為<div baukh="[object Object]"></div>testData.getAttribute('baukh'); // => "[object Object]"

可以從上面的代碼中看出,存進(jìn)去的是個(gè)Object,取出來的是Object.toString()所產(chǎn)出的字符串。

分析

在JS經(jīng)典類庫(kù)-jQuery中存在data方法是通過jQuery.cache的方式進(jìn)行數(shù)據(jù)存儲(chǔ),那么還有沒有其它方法可以實(shí)現(xiàn)?

由于使用場(chǎng)景不同,我想實(shí)現(xiàn)的方式是將數(shù)據(jù)直接存儲(chǔ)到DOM節(jié)點(diǎn)上,以達(dá)到使用時(shí)更方便簡(jiǎn)捷的目的。

那如何存儲(chǔ)? 變量testData存儲(chǔ)的是通過document.querySeletor('#test-data')獲取到的Element,而Element是Object的一個(gè)實(shí)例。通過[testData instanceof Object]可以進(jìn)行驗(yàn)證。

那么一切都簡(jiǎn)易了,即然是Object類型,那么就可以隨意的增刪自定義屬性。

通過在Element的原型上增加data方法來實(shí)現(xiàn)DOM擴(kuò)展

Element.prototype.data = function(key, value){ var _this = this,  _dataName = 'testData', // 存儲(chǔ)至DOM上的對(duì)象標(biāo)記, 這里只是測(cè)試用名  _data = {}; // 未指定參數(shù),返回全部 if(typeof key === 'undefined' && typeof value === 'undefined'){  return _this[_dataName]; } // setter if(typeof(value) !== 'undefined'){  // 存儲(chǔ)值類型為字符或數(shù)字時(shí), 使用attr執(zhí)行  var _type = typeof(value);  if(_type === 'string' || _type === 'number'){   _this.setAttribute(key, value);  }  _data = _this[_dataName] || {};  _data[key] = value;  _this[_dataName] = _data;  return this; } // getter else{  _data = _this[_dataName] || {};  return _data[key] || _this.getAttribute(key); }};

這里來試一下:

var testData = document.querySelector('#test-data');// 字符串類型測(cè)試testData.data('name', 'baukh');console.log(testData.data('name')); // => 'baukh'// 對(duì)象類型測(cè)試testData.data('info', {'name': 'baukh', 'age': 27});console.log(testData.data('info')); // => Object {name: "baukh", age: 27}

解決NodeList存儲(chǔ)

現(xiàn)在還有一個(gè)問題, 通過Element.prototype綁定的方法只支持Element類生效,而對(duì)NodeList類并無效果.

可以通過下面這些代碼進(jìn)行效果測(cè)試:

var testDataList = document.querySelectorAll('.test-data-list'); // 獲取的為NodeList 而非 ElementtestDataList.data('name', 'baukh'); // Uncaught TypeError: testDataList.data is not a function            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 湘阴县| 新余市| 亳州市| 黄骅市| 额尔古纳市| 荥阳市| 灌云县| 太白县| 东丽区| 永和县| 四会市| 自贡市| 连山| 建宁县| 华容县| 日照市| 遂宁市| 永福县| 滦平县| 天门市| 土默特左旗| 固安县| 武城县| 渝北区| 新民市| 剑阁县| 伊宁县| 乐陵市| 建湖县| 集安市| 上杭县| 兰考县| 睢宁县| 庐江县| 无锡市| 莱西市| 巴彦县| 班戈县| 鄄城县| 谢通门县| 措美县|