How to make variable accessible within jQuery .each() function?

closures, javascript, jquery, scope

Solution

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 why yours is failing is the `i` is inside of the function so it is reset every iteration. You would need to move it outside of the function for it to work.

Problem

This is and example of a frequent dilemma: how to make `markup` accessible inide this `.each()`? I'm more interested in learning how to access outer variables from within a closure than I am in this specific issue. I could fix this problem by assigning `markup` from inside the each function, but I'd rather learn a more elegant way to handle this kind of 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++; }); } ```

Original source