Home > Web Front-end > JS Tutorial > body text

Discussion on javascript closure parameter passing and event loop binding examples_javascript skills

WBOY
Release: 2016-05-16 16:52:01
Original
1032 people have browsed it

Today I saw a javascript question that bound events in a loop according to common sense, but the result was not what I wanted.

Copy code The code is as follows:

text< /a>


link
<script> <br>var as = document.getElementsByTagName('a'); <br>for ( var i = as.length; i--; ) { <br>as[i].onclick = function() { <br>alert(i); <br>return false; <br>} <br>} <br></script>

1. When clicking on the link in this code, the pop-up i’s are all -1. Why is this?

To put it simply, it is a function variable scope problem. If function() { alert(i); return false; } is regarded as a function a(); the variable i is not defined internally in a(), but it is used internally. , so I searched outside and found the i defined in the for loop. The click event started to be executed after the for loop was completed. After the execution, the value of i has become -1; so every time it pops up, it is -1;

2. The for loop with 2 parameters is also not common! Confuse?

 for (statement 1, statement 2, statement 3) {

  //todo

 }

a.for loop condition

Generally speaking, statement 1, statement 2, and statement 3 are all optional.

b. Statement 2:

Usually statement 2 is used to evaluate the conditions of the initial variables.

Statement 2 is also optional.

If statement 2 returns true, the loop will start again, if it returns false, the loop will end.

Tip: If you omit statement 2, you must provide a break inside the loop. Otherwise the cycle cannot be stopped. This may crash the browser.

c. Regarding i--judgment:

When judging i--true/false, i is first judged and then i-- is calculated. When entering the last judgment of i--, when i==0 was actually judged, i-- was executed again after the judgment, and the for loop terminated, so the value of i became -1;

 var i = 1;

 !!i--;//ture

Solution:
Copy code The code is as follows:

var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) {
(function (i){
as[i].onclick = function() {
alert(i);
return false;
}
})(i)
}

Or:
Copy code The code is as follows:

var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) {
var a = function(i){
as[i].onclick = function( ) {
alert(i);
return false;
}
}
a(i);
}

Other netizens solved it in 7 Method demo:
Copy code The code is as follows:


< ;head>

Closure Demonstration
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template