javaScript - 闭包

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9 </head>
10 <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
11 <script> 
12 
13 
14     // 需求 - 点击对应的选项出现对应的数字
15     // 实际效果:一次性循环了,每次都是最后加一
16     // 闭包前,每次都是弹出4
17     // $(document).ready(function () {
18     //     var spans = $("#divTest span");
19     //     for (var i = 0; i < spans.length; i++) {
20     //         spans[i].onclick = function () {
21     //             alert(i);
22     //         }
23     //     }
24     // });
25 
26 
27     // 需求 - 点击对应的选项出现对应的数字
28     // 实际效果:一次性循环了,每次都是最后加一
29     // 闭包后,得到想要的效果了,每次暂存1,而不是一次性循环
30     $(document).ready(function () {
31         var spans = $("#divTest span");
32         for (var i = 0; i < spans.length; i++) {
33             (function (num) {//匿名函数表达式 
34                 spans[i].onclick = function () {
35                     alert(num);
36                 }
37             })(i);//立即执行,并且把i的值传给num 
38         }
39     });
40 
41 
42 </script>
43 <style>
44     #divTest {
45         margin-top: 30px;
46         margin-bottom: 40px;
47     }
48 
49     span {
50         border-color: #3C0;
51         border-style: solid;
52         margin-bottom: 5px;
53         padding: 10px 30px 10px 30px;
54         border-radius: 10px
55     }
56 </style>
57 <title>无标题文档</title>
58 </head>
59 
60 <body>
61     <div id="divTest">
62         <span>0</span>
63         <span>1</span>
64         <span>2</span>
65         <span>3</span>
66     </div>
67 </body>
68 
69 </html>

猜你喜欢

转载自www.cnblogs.com/cisum/p/9247685.html