4

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++;
  });

}
6
  • markup is already accessible inside your anonymous function assigned in the .each, this is exactly what closures are. Commented Mar 7, 2013 at 22:00
  • 2
    At the start of each iteration of .each() you are resetting the variable i to 0. Commented Mar 7, 2013 at 22:01
  • I think the .each() is overused, its also quite slow compared to traditional iterators. Why are people so scared to use the good old for loop? Commented Mar 7, 2013 at 22:03
  • @sweetamylase The nice thing about it is this is what you are after. Commented Mar 7, 2013 at 22:06
  • @epascarello The this just referring to one of the elements in the collection, which could easily be var this = elements[i]. By wrapping the jQuery object around this $(this), this step alone takes a bigger performance hit than this = elements[i] Commented Mar 7, 2013 at 22:09

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.