HTML5_data-

HTML5_data-

HTML5_data-*    資料屬性

1. 自創  data-* attribute 

  •    屬性名稱不包含大寫字母

2. 取得data-* attribute 屬性值

  •     JS :  selector.dataset.*
  •     JQuery : $('selector').data('*')
  •     CSS : #selector tag[data-*="XX"] 

範例:

//HTML
<div id="slider" data-type="slideShow">
    <img class="photo" data-item="1" data-size="xs" src="http://...." />
    <img class="photo" data-item="2" data-size="lg" src="http://...." />
</div>

//JavaScript
  let slider = document.getElementById('slider');
  console.log(slider.dataset.type);   //slideShow
   
  let photo = document.querySelectorAll('.photo');
  console.log(photo[0].dataset.item);  //1
  console.log(photo[0].dataset.size);  //xs


//JQuery
  console.log($('slider').data('type'));   //slideShow


//CSS
  #slider img[data-size="xs"]
  {
    width: 400px;
  }

 

參考網址:https://pjchender.blogspot.com/2017/01/html-5-data-attribute.html