jquery - scope of variables in JavaScript callback functions -


I hope to code the code below to alert "0" and "1", but this is twice " 2 "warns me I do not understand the reason I do not know if this is a jQuery problem. Also, please help me edit the title and tag of this post if they are wrong.

  & lt; Html & gt; & Lt; Top & gt; & Lt; Script type = "text / javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" & gt; & Lt; / Script & gt; & Lt; Script type = "text / javascript" & gt; $ (Function (for (var i = 0; i & lt; 2; i ++) {$ .get ('http://www.google.com/', function) {alerts (i); });}}); & Lt; / Script & gt; & Lt; / Head & gt; & Lt; Body & gt; & Lt; / Body & gt; & Lt; / Html & gt;  

You are sharing a i variable in all Are the callbacks of

Because the variable is captured by context by closing javascript, the callback will always use the current value of i . Therefore, when the jQuery callback is performed after the execution of the loop Says, i will always be 2 .

You can reference the context of i as a separate function.

For example:

  function sender request (i) {$ .get ('http://www.google.com/', function () {warning (I);}); } (Var i = 0; i & lt; 2; i ++) {sendRequest (i); }  

In this way, each callback will have a separate termination with a different i parameter.


Comments