javascript - .forEach loop: use variable -


I am looping through a set of 16 IDs and assigning a eventListener to each I am doing I want to send a number to my php file (1 for first ID, 2 for others, etc, etc.), but it seems that i is more dynamic than I want. Each ID sends 17 . Get an internal element by klasses.forEach (function (klass) {var svgElement = svgDoc.getElementById (klass); // id svgElement .addEventListener ("mouseup", function () {$ $ ("#modLSpan"); .ax ((type: "POST", url: "buildService.php", data: {"service": i}}). (Function (msg) {alert (Layerre [i] ) .HTML (msg); $ ("# modmodal"). Modal ();})}}); i ++;});

How can I set each to a specific number? I have also tried:

  var lameArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 16]; ... data: {"service": lameArray [i]}    

Code> I ? The problem is that i is a global variable, or a variable outside circle for , so when the mouseup event begins The element in the value i is used, and it was not when the event listener was defined.

Note that because you are using forEach , the callback function is actually called with another parameter, which is a counter, you can use it:

  Clauses. EEF (function (class, i) {...});   

Now, i is a variable in the field forEach , and works in your objectives ( forEach callback function also calls with the third parameter, which is the collection - klasses in your case.)

Note

  $ Each (clas, function (i), klass {$ ("#" + klass) .mouseup (function () {$ .ajax ({Type: "POST", url: "buildService.php", Data: {Service: I + 1} ...});});});    

Comments

Popular posts from this blog

Python SQLAlchemy:AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'schema' -

java - How not to audit a join table and related entities using Hibernate Envers? -

mongodb - CakePHP paginator ignoring order, but only for certain values -