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++;
});
}
.each()you are resetting the variableito 0..each()is overused, its also quite slow compared to traditional iterators. Why are people so scared to use the good oldforloop?thisis what you are after.thisjust referring to one of the elements in the collection, which could easily bevar this = elements[i]. By wrapping the jQuery object around this$(this), this step alone takes a bigger performance hit thanthis = elements[i]