How to make a variable available in jQuery.each () function?

This is an example of frequent dilemmas: how to make markup available in this .each() ?

I'm more interested in learning how to access external variables from a closure than in this particular problem. I could solve this problem by assigning markup from within each function, but I would prefer a more elegant way to deal with such a problem.

 // hide form & display markup function assessmentResults(){ // get assessment responses var markup = parseForm(); // show assessment results to user $('#cps-assess-form fieldset').each( function() { var q = $(this).find('.fieldset-wrapper'); var i = 0; // hide form questions q.slideUp(); // insert markup $('<div>'+markup[i]+'</div>').insertAfter(q); i++; }); } 
+4
source share
1 answer

Read the docs , it already has an index!

 .each( function(index, Element) ) 

No need for i

 $('#cps-assess-form fieldset').each( function(index) { var q = $(this).find('.fieldset-wrapper').slideUp(); $('<div/>').html(markup[index]).insertAfter(q); }); 

The reason you failed is because i inside the function, so it reset every iteration. You will need to move it outside the function for it to work.

+5
source

All Articles