两种方法
- 元素节点.属性 或 元素节点[" "]
例:
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="box">中国</div>
<script>
var box = document.getElementsByClassName("box")[0];
box.aaaa = "1111";
</script>
</body>
- 元素节点.方法
例:
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="box">中国</div>
<script>
var box = document.getElementsByClassName("box")[0];
box.setAttribute("aaaa","2222");
console.log(box.setAttribute("aaaa", "2222"));
</script>
</body>
但是,当书写事件驱动程序时:
只有以下是正确的
<style>
button {
width: 80px;
height: 60px;
}
.current {
background-color: yellow;
}
</style>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<button>按钮5</button>
<script>
var btn = document.getElementsByTagName("button");
btn[0].setAttribute("backgroundColor","yellow");
for(var i=1;i<btn.length;i++){
btn[i].onmouseover = function(){
this.className = "current";
}
}
</script>
</body>
以下两种,错误提示均为:Cannot set property 'className' of undefined
Cannot read property 'setAttribute' of undefined,不知道为啥
<script>
var btn = document.getElementsByTagName("button");
// btn[0].setAttribute("backgroundColor","yellow");
for(var i=1;i<btn.length;i++){
btn[i].onmouseover = function()
// btn[i].className = "current";错误
// btn[i].setAttribute("backgroundColor","yellow"); 错误
}
}
</script>
原因为:运行完成后,i变为5,因为未触发事件之前,先进行for循环,只加载函数名,不加载函数体。即只遍历li[i].onmouseover部分,而函数体的内容并未运。以下列子alert,即I均为5
<script>
var li = document.getElementsByTagName("li");
var span = document.getElementsByTagName("span");
for(var i=0;i<li.length;i++){
li[i].onmouseover = function(){
this.className = "bgc";
alert(i);
}
li[i].onmouseout = function(){
this.className = "";
}
}
</script>