相关博客:https://blog.csdn.net/MixedSignals/article/details/105155812
JavaScript中对于标签属性的设定分成若干中情况, 比较复杂没有固定的用法,需要慢慢的理解和记忆
标签对象.setAttribute(属性 , 属性值)
①标签本身具有属性
console.dir(标签对象) 可以看到的都可以通过标签直接操作,不一定要用 setAttribute()
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div1{color: red;}
</style>
</head>
<body>
<div>我是div</div>
<script>
var oDiv = document.querySelector('div');
console.dir(oDiv);
oDiv.className = 'div1'; //可以直接操作
oDiv.setAttribute('class' , 'div1'); // 使用setAttribute()也可以
</script>
</body>
②单选和复选框
使用getAttribute和setAttribute,如果直接使用getAttribute来获取标签的属性值,获取的结果是null。如果在标签中设定checked属性,获取的是属性的属性值。如果不写属性值,即使有默认选中效果,获取的也是空字符串。只有设定了内容,获取的结果才是设定的内容
oRadio.setAttribute('checked' , 'checked'); // 可以
oRadio.setAttribute('checked' , true); // 可以
//设定的和获取的都是字符串形式,除了true/false设定的是布尔值
//与直接通过标签本身的属性来获取是不同的
<body>
<input type="radio">
<script>
var oRadio = document.querySelector('[type="radio"]');
console.dir(oRadio);
oRadio.setAttribute('checked' , true);
console.log(oRadio.getAttribute('checked'));
oRadio.checked = 'checked'; // 可以
oRadio.checked = true; // 可以
console.log(oRadio.checked); // 获取的是 true / false 布尔值
</script>
</body>
③其他一些标签的属性
定义之后是不会出现在标签本身属性上,但是会出现在标签的内容上,也不能直接来获取。有些低版本浏览器是可以设定和获取的,例如 name属性
<body>
<span index="第一个">我是span</span>
<script>
var oSpan = document.querySelector('span');
oSpan.setAttribute('name' , 'spanspan')
oSpan.setAttribute('index' , '第一个')
console.dir(oSpan);
console.log(oSpan.name)
console.log(oSpan.index)
</script>
</body>