自定义属性的设置,获取和移除

本身html标签没有这个属性,自己(程序员)添加的,----自定义属性—为了存储一些数据
设置自定义属性:setAttribute(“属性的名字”,“属性的值”);
获取自定义属性的值:getAttribute(“属性的名字”)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        ul{
    
    
            list-style: none;
            cursor: pointer;
        }
    </style>
    <script src="common.js"></script>
</head>
<body>
<ul id="ll">
    <li>大一</li>
    <li>大二</li>
    <li>大三</li>
    <li>大四</li>
</ul>
<script>
    //本身html标签没有这个属性,自己(程序员)添加的,----自定义属性---为了存储一些数据
    //设置自定义属性:setAttribute("属性的名字","属性的值");
    //获取自定义属性的值:getAttribute("属性的名字")
    //获取所有的li标签,然后为每个标签中动态的添加自定义属性和值
    //点击的时候获取该标签的自定义属性的值
    var list=my$("ll").getElementsByTagName("li");
    for(var i=0;i<list.length;i++){
    
    
        list[i].setAttribute("score",String((i+1)*49));
        list[i].onclick=function(){
    
    
            alert(this.getAttribute("score"));
        };
    }
</script>
</body>
</html>

移除自定义属性或者某个元素自带的属性:removeAttribute(“属性的名字”)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
    
    
            width: 100px;
            height: 100px;
            background-color: red;
        }
        .cls{
    
    
            background-color: blue;
        }
    </style>
    <script src="common.js"></script>
</head>
<body>
<input type="button" value="按钮" id="btn">
<div  score="10" class="cls"></div>
<script>
    //移除自定义属性:removeAttribute("属性的名字")
    my$("btn").onclick=function () {
    
    
        document.getElementsByTagName("div")[0].removeAttribute("score");
        document.getElementsByTagName("div")[0].removeAttribute("class");
    };
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/dwjdj/article/details/104247211