HTML DOM 教程---操作自定义属性(2)

发布于:2024-10-18 ⋅ 阅读:(43) ⋅ 点赞:(0)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="box" kerwin="hello"> hello </div>
    <input type="text" value="111111" id="username">

    <input type="checkbox" checked="checked" id="rember">
    <img src="" alt="" id="photo">
    <ul>
        <li>111111</li>
        <li>222222</li>   
        <li>333333</li>
    </ul>
    <!-- 自定义标签data- -->
    <div id="box2" data-kerwin="hello" data-tiechui="hello2" data-xiaoming="hello3"></div>
    <script>

        // 自定义属性
        // 设置属性
        box.setAttribute("tiechui","111111111")
        // 获取属性 
        console.log(box.getAttribute("tiechui"))

        // 删除属性
        box.removeAttribute("tiechui")
        box.removeAttribute("kerwin")

        // var oitems = document.getElementsByTagName("li")
        // for(var i=0;i<oitems.length;i++){
        //     oitems[i].setAttribute("kkindex",i)
        // }

        // h5  data-自定义属性的特有标签
        // 获取
        console.log(box2.dataset)
        // 设置
        box2.dataset.xiaoming = "hello3333"
        // 删除
        delete box2.dataset.xiaoming
        delete box2.dataset.kerwin
        delete box2.dataset.tiechui

        var oitems = document.getElementsByTagName("li")
        for(var i=0;i<oitems.length;i++){
            oitems[i].dataset.index = i
        }
    </script>
</body>
</html>