美文网首页
html question

html question

作者: IAmWhoAmI | 来源:发表于2016-06-24 15:05 被阅读41次

    7.What are data- attributes good for?

    <ul id="vegetable-seeds">  
      <li data-spacing="10cm" data-sowing-time="March to June">Carrots</li>  
      <li data-spacing="30cm" data-sowing-time="February to March">Celery</li>  
      <li data-spacing="3cm" data-sowing-time="March to September">Radishes</li>
    </ul>
    

    普通用法:

    <div id='strawberry-plant' data-fruit='12'></div>
    
    <script>
    // 'Getting' data-attributes using getAttribute
    var plant = document.getElementById('strawberry-plant');
    var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
    
    // 'Setting' data-attributes using setAttribute
    plant.setAttribute('data-fruit','7'); // Pesky birds
    </script>
    
    // Select all elements with a 'data-flowering' attribute
    document.querySelectorAll('[data-flowering]');
    // Select all elements with red leaves
    document.querySelectorAll('[data-foliage-colour="red"]');
    

    data-特性:

    <div id='sunflower' data-leaves='47' data-plant-height='2.4m'></div>
    <script>
    // 'Getting' data-attributes using dataset 
    var plant = document.getElementById('sunflower');
    var leaves = plant.dataset.leaves; // leaves = 47;
    
    // 'Setting' data-attributes using dataset
    var tallness = plant.dataset.plantHeight; // 'plant-height' -> 'plantHeight'
    plant.dataset.plantHeight = '3.6m';  // Cracking fertiliser
    </script>
    

    data-属性用于存储某些特定的数据,而无需频繁地调用ajax向后台请求数据。
    主要是解决,属性不够用。但是有多余的信息需要存储。
    参考内容

    相关文章

      网友评论

          本文标题:html question

          本文链接:https://www.haomeiwen.com/subject/fmmmdttx.html