在HTML5中定制数据属性

下面的例子展示了你如何在HTML5中定制数据的属性。使用dataset属性和getAttribute()方法。

<!DOCTYPE html>
<html>
<head>
    <title>Using custom data attributes in HTML5</title>
    <style type="text/css">
        th {
            font-style: italic;
            font-weight: normal;
            text-align: right;
        }
    </style>
</head>
<body>
 
    <table id="status" data-city="San Francisco" data-zipCode="94121-1437" data-user-name="Peter">
        <tr>
            <th>dataset.zipcode:</th>
            <td id="cell1"></td>
        </tr>
        <tr>
            <th>dataset['zipcode']:</th>
            <td id="cell2"></td>
        </tr>
        <tr>
            <th>getAttribute('data-zipCode'):</th>
            <td id="cell3"></td>
        </tr>
        <tr>
            <th>dataset.userName:</th>
            <td id="cell4"></td>
        </tr>
        <tr>
            <th>dataset['userName']:</th>
            <td id="cell5"></td>
        </tr>
        <tr>
            <th>getAttribute('data-user-name'):</th>
            <td id="cell6"></td>
        </tr>
    </table>
    <button id="btn" onclick="btn_clickHandler(event);">Click to get dataset zipCode and user-name</button>
 
    <script type="text/javascript">
        function btn_clickHandler(event) {
            var stat = document.getElementById("status");
 
            document.getElementById("cell1").innerText = stat.dataset.zipcode;
            document.getElementById("cell2").innerText = stat.dataset["zipcode"];
            document.getElementById("cell3").innerText = stat.getAttribute("data-zipCode");
 
            document.getElementById("cell4").innerText = stat.dataset.userName;
            document.getElementById("cell5").innerText = stat.dataset["userName"];
            document.getElementById("cell6").innerText = stat.getAttribute("data-user-name");
        }
    </script>
 
</body>
</html>

源码下载:

using-custom-data-attributes-in-html5.zip

相关推荐