6、自定义属性 - HTML5&CSS3.0基础部分-xyphf

自定义属性1——设置

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
<script>
window.onload = function(){
    var oBtn = document.querySelector('input[type=button]');
    alert(oBtn.dataset.index);
};
</script>
</head>
<body>
<input type="button" value="按钮" data-index="1" />
</body>
</html>

自定义属性2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义属性</title>
<script>
window.onload = function(){
    var oBtn = document.querySelector("input[type=button]");

    //设置
    oBtn.setAttribute("data-b","b");

    oBtn.dataset.a = 12;

    alert(oBtn.dataset.a);
}
</script>
</head>
<body>
<input type="button" value="按钮" data-index="1"/>
</body>
</html>

自定义属性3——不遵循配对原则

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义属性——不遵循配对原则</title>
<script>
    window.onload = function(){
        var oBtn = document.querySelector("input[type=button]");
        //不遵循配对原则
        oBtn.setAttribute("data-b","b");
        alert(oBtn.dataset.b);

        oBtn.dataset.a = 12;
        alert(oBtn.getAttribute("data-a"));
    }
</script>
</head>
<body>
<input type="button" value="按钮" data-index="1"/>
</body>
</html>

自定义属性4——遍历循环

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
<script>
window.onload = function(){
    var oBtn = document.querySelector("input[type=button]");

    //遍历 迭代 --》循环
    for(var name in oBtn.dataset){
        alert(name + "|" + oBtn.dataset[name]);
    }
};
</script>
</head>
<body>
<input type="button" value="按钮" data-index="1" data-a="a" data-b="b" /> 
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值