使用闭包。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
button{
width: 100px;
height: 50px;
background-color: #4CAF50;
padding: 0px 12px;
font-size: 14px;
color: white;
border: none;
}
</style>
</head>
<body>
<div class="container">
<button type="button">按钮1</button>
<button type="button">按钮2</button>
<button type="button">按钮3</button>
<button type="button">按钮4</button>
<button type="button">按钮5</button>
</div>
<script>
var butt = document.getElementsByTagName("button");
// 使用闭包,为每一个按钮开辟一块内存存储变量num
function getNum(){
var num = 0;
return(function(){
num++;
alert("您点击了我"+num+"次");
})
}
// 为每一个按钮添加点击事件
for(var i = 0; i<butt.length; i++){
butt[i].onclick = getNum();
}
</script>
</body>
</html>