代码演示:
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]> <html class="no-js"> <!--<![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>js设置setAttribute、获取getAttribute、删除removeAttribute详细讲解 </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<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", "number")
//自定义属性值
input.setAttribute("aa", "bb")
}
function getClick() {
// getAttribute 输出input的type类型是password
console.log(input.getAttribute("type"));
}
//removeAttribute 删除input的value值
function deleteClick() {
input.removeAttribute("value")
input.removeAttribute("type")
input.removeAttribute("ccc")
}
</script>
</html>
理解:
## 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
删除属性值;
如果移除不存在的属性值,并不会报错的哈。
在echarts中就会使用removeAttribute这个方法
主要是处理echarts第二次不会渲染
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)