效果图:
代码
<!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 >点我是0</button>
<button >点我是1</button>
<button >点我是2</button>
<br>
<button >点我是3</button>
<button >点我是4</button>
<button >点我是5</button>
<script>
var a=document.getElementsByTagName('button')
for(var index=0;index<a.length+1;index++){
(function(i){
a[index].onclick=function(){
alert("我就是"+i+"号按钮")
}
})(index)
}
</script>
</body>
</html>
利用alert可以弹出弹出层,再加上dom和for循环就可以实现点击哪个按钮就出现什么数字了
还有一种写法,但是比较麻烦:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>按钮弹窗示例</title>
</head>
<body>
<button onclick="showAlert(1)">按钮0</button>
<button onclick="showAlert(2)">按钮1</button>
<button onclick="showAlert(3)">按钮2</button>
<button onclick="showAlert(4)">按钮3</button>
<button onclick="showAlert(5)">按钮4</button>
<button onclick="showAlert(6)">按钮5</button>
<script>
function showAlert(num) {
let i = 1;
while (i <= num) {
++i;
}alert(i);
}
</script>
</body>
</html>
这种写法就是在每一个button里写onclick=showAlert(num)函数