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

49 阅读1分钟

自定义属性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>