js版:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<script>
// 获取所有button按钮
var btn=document.getElementsByTagName("button")
// 遍历所有button按钮
for(var i=0;i<btn.length;i++){
// 将i赋值给index
btn[i].index = i
// 给每个button按钮添加单机事件
btn[i].onclick=function(){
// 获取单机的button按钮索引值
console.log(this.index);
}
}
</script>
</body>
</html>
let版:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<script>
// 获取所有button按钮
let btn=document.getElementsByTagName("button")
// 遍历所有button按钮
for(let i=0;i<btn.length;i++){
// 给每个button按钮添加单机事件
btn[i].onclick=function(){
// 获取单机的button按钮索引值
console.log(i);
}
}
</script>
</body>
</html>