<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="123">
<input type="button" value="123">
<input type="button" value="123">
<input type="button" value="123">
<input type="button" value="123">
<script>
var btoObjs = document.getElementsByTagName("input");
for (var i = 0; i < btoObjs.length; i++) {
btoObjs[i].onclick = function () {
for (var j = 0; j < btoObjs.length; j++) {
btoObjs[j].value = "123";
}
// console.log(i); 这里也是5
this.value = "234";//这里用btoObjs[i].value是错误的
};
}
console.log(i);//这里是5
</script>
</body>
</html>
思路:遍历所有button,添加点击事件,事件函数:遍历所有button,重置所有value的值,然后用this添加value值;
为什么要用this呢?而不是用btoObjs[i].value呢?
第一次for循环是网页加载时就加载了,当加载完时i的值是5;
为什么是5呢,不应该是4吗?
我这里有5个button,所以最后一轮循环i为4,但是系统不知道我还有没有,所以还要下一轮判断,i++,然后判断i<btoObjs.length。
答案肯定是否的,跳出for循环,所以最后i是5。
当点击按钮后,这时函数中的代码才会执行,如果用btoObjs[i].value,此时i就是5,但是最多也就是4,所以会报错。所以要用this。