In JS, when you write a for loop, the internal loop variable I is actually saved in the function or class it runs, so you will find that when you bind events to elements in batches, the value of I = The Last loop variable appears. This is very embarrassing. The solution has two minutes,
The idea is: Save the loop variable, instead of putting its scope in the whole function, but in the loop body.
1. Use closures (Open Baidu: www.baidu.com if you do not understand closures)
2. Use the with keyword. The with syntax is with (obj) {// so that you can directly access the properties of obj without adding obj. XXX}
Sample Code:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Untitled Page </title>
<Script type = "text/javascript" src = "jquery-1.7.2.js"> </script>
<Script type = "text/javascript" language = "javascript">
$ (Document). ready (function (){
Function Ev (I ){
This. index = I;
This. click = function (){
Alert (this. index );
}
}
For (var k = 1; k <4; k ++ ){
// Closure function 1
// (Function (x ){
// $ ("# Div" + x). click (function (){
// F (x );
//});
//} (K ));
// Use the with keyword
With ({I: k }){
$ ("# Div" + I). click (function (){
F (I );
});
}
}
Var f = function (m ){
Alert (m );
}
});
</Script>
</Head>
<Body>
<Div id = "div1"> 1
</Div>
<Div id = "div2"> 2
</Div>
<Div id = "div3"> 3
</Div>
</Body>
</Html>