代碼演示:
<!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設(shè)置setAttribute、獲取getAttribute、刪除removeAttribute詳細(xì)講解 </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="點(diǎn)擊設(shè)置">
<input type="button" onClick="getClick()" value="點(diǎn)擊查詢">
<input type="button" onClick="deleteClick()" value="點(diǎn)擊刪除">
</div>
<script>
var input = document.getElementById('inputdemo');
// setAttribute 設(shè)置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類型)。您希望添加的屬性值
使用場(chǎng)景:可以設(shè)置元素的屬性類型。
<input value="3652" id="inputdemo" type="password">
最初是密碼框,我們使用這個(gè)方法可以設(shè)置為file類型
同時(shí)它也可以設(shè)置自定義的屬性值
比如
inputdemo.setAttribute("aa", "bb")
## getAttribute
獲取元素的屬性值,如果存在返回對(duì)應(yīng)的值
不存在返回null
<input value="3652" id="inputdemo" type="password">
返回password哈
console.log(input.getAttribute("type"));
由于不存在aa這個(gè)屬性,所以返回null
console.log(input.getAttribute("aa"));
## removeAttribute
刪除屬性值;
如果移除不存在的屬性值,并不會(huì)報(bào)錯(cuò)的哈。
在echarts中就會(huì)使用removeAttribute這個(gè)方法
主要是處理echarts第二次不會(huì)渲染
浙公網(wǎng)安備 33010602011771號(hào)