代码-JS之闭包点击输出下标
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!--点击页面中的li,能够输出它的下标-->
<ul>
<li>00000000</li>
<li>11111111</li>
<li>22222222</li>
<li>33333333</li>
</ul>
<script>
//定义闭包函数输出结果
function outFun(x){
//console.log(i);
function inFun(){
console.log(x);
}
return inFun;
}
//找到节点
var lis = document.getElementsByTagName('li');
//遍历数组
for(var i=0; i<lis.length; i++){
//绑定点击事件,并调用outFun函数
lis[i].onclick = outFun(i);
}
</script>
</body>
</html>
Copyright [2018] by [羊驼可以吃吗] form [https://www.cnblogs.com/phpisfirst/]