js设置setAttribute、获取getAttribute、删除removeAttribute详细讲解


setAttribute的理解

所有主流浏览器均支持 setAttribute() 方法。
element.setAttribute(keys,cont)

keys==>必需(String类型)。您希望添加的属性的名称
cont==>必需(String类型)。您希望添加的属性值 

使用场景:可以设置元素的属性类型。
<input value="3652" id="inputdemo" type="password">
最初是密码框,我们使用这个方法可以设置为file类型
同时它也可以设置自定义的属性值
比如
inputdemo.setAttribute("aa", "bb")

getAttribute

获取元素的属性值,如果存在返回对应的值
不存在返回null
<input value="3652" id="inputdemo" type="password">
返回password哈
console.log(input.getAttribute("type"));
由于不存在aa这个属性,所以返回null
console.log(input.getAttribute("aa"));

removeAttribute

删除属性值;
如果移除不存在的属性值,并不会报错的哈。
在echaers中就会使用removeAttribute这个方法
主要是处理echarts第二次不会渲染

通过案例了解这几个值

<body>
    <div>
        <input value="3652" id="inputdemo" type="password">
        <input type="button" onClick="setClick()" value="点击设置">
        <input type="button" onClick="getClick()" value="点击查询">
        <input type="button" onClick="deleteClick()" value="点击删除">
    </div>
    <script>
        var input = document.getElementById('inputdemo');
        // setAttribute 设置input的type为file
        function setClick() {
            input.setAttribute("type", "file")

            //自定义属性值
            input.setAttribute("aa", "bb")
        }

        // getAttribute 输出input的type类型是password
        function getClick() {
            console.log(input.getAttribute("type"));
        }

        //removeAttribute 删除input的value值
        function deleteClick() {
            input.removeAttribute("value")
            input.removeAttribute("type")
            input.removeAttribute("ccc")
        }
    </script>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM