html5——自訂屬性

來源:互聯網
上載者:User

標籤:dataset屬性   org   迴圈   欄位   get   attribute   結構   方式   jquer   

自訂屬性:添加首碼“data-”

dataset屬性:添加自訂屬性後,通過元素的dataset屬性來訪問自訂屬性的值(屬性名稱沒有data-首碼)
data-name:dataset.name
data-name-first:dataset.nameFirst

 

html結構:

1 <div id="div1" data-name="china" data-name-all="chinese">div</div>

 

1.利用 getAttribute、setAttribute 存取 dataset

 1 var oDiv = document.getElementById("div1"); 2  3 //get 4 console.log(oDiv.getAttribute("data-name")); // china 5 console.log(oDiv.getAttribute("data-name-all")); // chinese 6  7  8 //set 9 oDiv.setAttribute("data-name","hello");10 oDiv.setAttribute("data-name-all","hi");

這樣就可以以一種更相容的方式,來存取dataset資料。所做出的任何更改,都是可以即時反映到元素data屬性上的。

但是這種方法比較低端,如果遇到多個data-*自訂欄位,想要一次全部擷取所有的data屬性並封裝成對象的話,還必須做一個迴圈,很麻煩。

 

2.利用 dataset API 存取 dataset

 1 var oDiv = document.getElementById("div1"); 2  3 //get 4 console.log(oDiv.dataset.name); // china 5 console.log(oDiv.dataset.nameAll); // chinese 6  7  8 //set 9 oDiv.dataset.name = ‘hello‘;10 oDiv.dataset.nameAll = ‘hi‘;

 

 

3.利用 jQuery.attr 方法存取 dataset

1 //get2 console.log($(‘#div1‘).attr(‘data-name‘)); // china3 console.log($(‘#div1‘).attr(‘data-name-all‘)); // chinese4 5 6 //set7 $(‘#div1‘).attr(‘data-name‘, ‘hello‘);8 $(‘#div1‘).attr(‘data-name-all‘, ‘hi‘);

 

 

4.利用 jQuery.data 方法存取 dataset

1 //get2 console.log($(‘#div1‘).data(‘name‘)); // china3 console.log($(‘#div1‘).data(‘nameAll‘)); // chinese4 5 6 //set7 $(‘#div1‘).data(‘name‘, ‘hello‘);8 $(‘#div1‘).data(‘nameAll‘, ‘hi‘);

這樣的方法也能出色的存取data屬性,但是需要注意,jQuery.data對data資料做出的更改,不會反映到HTML元素data屬性上。

 

html5——自訂屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.