当触发点击事件,一个简单的例子。
<!DOCTYPE html>
<html>
<head><title>闭包创建数组</title><meta charset="utf-8"><script type="text/javascript">window.onload = function (){var lis = document.getElementsByTagName('li');for (var i = 0; i < lis.length; i++) {lis[i].onclick = function () {console.log(this.innerHTML);};}}</script>
</head>
<body><h2>闭包点击事件</h2><ul><li>奔驰</li><li>宝马</li><li>奥迪</li></ul>
</body>
</html>
但是,当我想要得到循环外的变量值。
<!DOCTYPE html>
<html>
<head><title>闭包创建数组</title><meta charset="utf-8"><script type="text/javascript">window.onload = function (){var lis = document.getElementsByTagName('li');var price = [1, 10, 100];for (var i = 0; i < lis.length; i++) {lis[i].onclick = function () {console.log(this.innerHTML+ '的价格:' + price[i]);};}}</script>
</head>
<body><h2>闭包点击事件</h2><ul><li>奔驰</li><li>宝马</li><li>奥迪</li></ul>
</body>
</html>
由于当我点击的时候,i的值已经是3了,所以会undefined。现在的问题就是怎么才能在每次循环中把i的值保存下来。
<!DOCTYPE html>
<html>
<head><title>闭包创建数组</title><meta charset="utf-8"><script type="text/javascript">window.onload = function (){var lis = document.getElementsByTagName('li');var price = [1, 10, 100];for (var i = 0; i < lis.length; i++) {lis[i].onclick = (function (n) {console.log("i:"+i+";n:"+n);return function () {console.log(this.innerHTML+ '的价格:' + price[n]);};})(i);}}</script>
</head>
<body><h2>闭包点击事件</h2><ul><li>奔驰</li><li>宝马</li><li>奥迪</li></ul>
</body>
</html>
闭包的经典回答应该是:延长局部变量的生命周期