A netizen asked a question, such as the next HTML, why each output is 5, instead of clicking on each p, alert out the corresponding 1,2,3,4,5.
- <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
- <title> Closures Demo </title>
- <script type= "Text/javascript" >
- function init () {
- var pary = document.getElementsByTagName ("P");
- for (var i=0; i<pary.length; i++) {
- Pary[i].onclick = function () {
- alert (i);
- }
- }
- }
- </script>
- <body onload= "Init ();" >
- <p> Product One </p>
- <p> Products Two </p>
- <p> Products Three </p>
- <p> Products Four </p>
- <p> Products Five </p>
- </body>
There are several ways to solve the problem
1. Save the variable i to each paragraph object (p)
- function init () {
- var pary = document.getElementsByTagName ("P");
- for (var i=0; i<pary.length; i++) {
- PARY[I].I = i;
- Pary[i].onclick = function () {
- alert (THIS.I);
- }
- }
- }
2. Save the variable i in the anonymous function itself
- function Init2 () {
- var pary = document.getElementsByTagName ("P");
- for (var i=0; i<pary.length; i++) {
- (Pary[i].onclick = function () {
- alert (ARGUMENTS.CALLEE.I);
- }). i = i;
- }
- }
3, add a layer of closure, I in the form of function parameters passed to the inner layer function
- function Init3 () {
- var pary = document.getElementsByTagName ("P");
- for (var i=0; i<pary.length; i++) {
- (function (ARG) {
- Pary[i].onclick = function () {
- Alert (ARG);
- };
- }) (i);//call-time parameter
- }
- }
4, add a layer of closure, I in the form of local variables passed to the memory function
- function Init4 () {
- var pary = document.getElementsByTagName ("P");
- for (var i=0; i<pary.length; i++) {
- (function () {
- var temp = local variable when i;//called
- Pary[i].onclick = function () {
- Alert (temp);
- }
- })();
- }
- }
5, add a layer of closures, return a function as a response event (note the subtle difference from 3)
- function Init5 () {
- var pary = document.getElementsByTagName ("P");
- for (var i=0; i<pary.length; i++) {
- Pary[i].onclick = function (ARG) {
- return function () {//Returns a functional
- Alert (ARG);
- }
- } (i);
- }
- }
6, with the function implementation, in fact, each generation of an instance of the functions will produce a closure
- function Init6 () {
- var pary = document.getElementsByTagName ("P");
- for (var i=0; i<pary.length; i++) {
- Pary[i].onclick = new Function ("alert (" + i + ");"); /new one function instance at a time
- }
- }
7, with the function to achieve, pay attention to the difference with 6
- function Init7 () {
- var pary = document.getElementsByTagName ("P");
- for (var i=0; i<pary.length; i++) {
- Pary[i].onclick = Function (' Alert (' +i+ ') ')
- }
- }
this blog goes from other blogs
JavaScript for loop closure "Go"