<body>
<button id="btn">我是一个按钮</button>
<script>
window.onload = function (ev) {
var btn = document.getElementById("btn");
// btn.onclick = function (ev2) {
// // alert(0);
// window.location.href="http://www.baidu.com";
// }
btn.addEventListener(‘click‘,function (ev1) {//添加事件,第一个参数是如何触发第二个参数的事件(函数)
alert(0);
})
}
</script>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D34_2_UsageOfClosures</title>
<style>
*{
margin:0;
padding:0;
vertical-align:top;
}
body{
background:url("img/background.jpg") no-repeat;
background-size:cover;
}
#box ul{
display:flex;
justify-content: space-around;
align-items:center;
cursor:pointer;
}
img{
width:250px;
}
li{
list-style: none;
}
</style>
</head>
<body>
<div id="box">
<ul>
<li><img src="img/img_01.png" ></li>
<li><img src="img/img_02.png" ></li>
<li><img src="img/img_03.png" ></li>
<li><img src="img/img_04.png" ></li>
<li><img src="img/img_05.png" ></li>
</ul>
</div>
<script>
window.onload = function (ev) {
//1.获取标签
var box = document.getElementById("box");
var allList = box.getElementsByTagName("li");
//2.遍历监听
for(var i=0;i<allList.length;i++){
//2.1取出单个li标签
var sLi = allList[i];
// sLi.index = i+1;//给予一个属性index
// //2.2监听点击事件
// sLi.addEventListener("click",function (ev2) {
// document.body.style.background =‘url("img/img_0‘ + this.index + ‘.png") no-repeat‘;
// });
//也可以使用如下闭包的方式
(function (index) {
sLi.addEventListener("click",function (ev3) {
document.body.style.background =‘url("img/img_0‘ + index + ‘.png") no-repeat‘;
});
})(i+1)
}
}
</script>
</body>
</html>
https://github.com/ruigege66/JavaScript/blob/master/D34_1_SomethingSupplyment.html
https://github.com/ruigege66/JavaScript/blob/masterD34_2_UsageOfClosures.html
https://www.cnblogs.com/ruigege0000/
https://blog.csdn.net/weixin_44630050?t=1
JavaScript连载34-addEventListener函数以及闭包的使用
原文:https://www.cnblogs.com/ruigege0000/p/13722004.html