<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload=function(){
var btns = document.getElementsByTagName("button");
// 遍历加监听
// -----------有问题--------------
/* for (var i = 0, length = btns.length; i < length; i++) {
var obj = btns[i];
obj.onclick=function(){
alert("第" + (i+1) + "个");//第4个
}
} */
// ---------------解决一:保存下标--------------------
/* for (var i = 0, length = btns.length; i < length; i++) {
var btn = btns[i];
// 将btn所对应的下标保存在btn上
btn.index=i;
btn.onclick = function () {
alert("第" + (this.index+1) + "个");
}
} */
//-------------------解决二:利用闭包----------------
for (var i = 0, length = btns.length; i < length; i++) {
(function (i){
var btn = btns[i];
btn.onclick = function () {
alert("第" + (i + 1) + "个");
}
})(i);
}
};
</script>
</head>
<body>
<button>测试1</button>
<button>测试2</button>
<button>测试3</button>
<!-- 需求:点击某个按钮,提示“点击的是第n个按钮” -->
</body>
</html>


