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>