在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" οnclick="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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值