1

I am trying to create a dynamic accordion. My problem is that I can not seem to get a reference to the i variable inside the for loop. I know it is a scope problem but I thought this closure would do the trick.... Please someone help me out as this is driving me completely insane.

jQuery(function(){

  var tables = jQuery('table');
  var tableHeadings = jQuery('h3');

  for(i =0 , ii = tableHeadings.length; i < ii; i++){
     (function(){ 

        var index = i;
        tables.eq(index).addClass('table-' + index);

        tableHeadings.eq(index).click(function(){   
            tables.eq(index).slideToggle(); 
        });

      })();
    }  
});
7
  • Have you got a live example of where this fails? This should work AFAIK. Commented Dec 19, 2011 at 15:49
  • Why would you need a closure here? Just execute the code in the for loop directly. Commented Dec 19, 2011 at 15:50
  • @asawyer: Because otherwise in the click handler, i (or index) would always be the last value. Commented Dec 19, 2011 at 15:50
  • @Matt Ah I see. Why not $("h3").each(function(i,e){ ... }); then, instead of the awkward for loop? Commented Dec 19, 2011 at 15:52
  • @asawyer: That'd work as well, have to ask `@RobertRubyII why he elected not to use it :). Commented Dec 19, 2011 at 15:56

1 Answer 1

4

Better yet:

tableHeadings.each(function(index, element) {
  tables.eq(index).addClass('table-' + index);

  tableHeadings.eq(index).click(function() {   
    tables.eq(index).slideToggle(); 
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Dunno if it is better to use tableHeadings.eq(index) or $(this)
good point. I just copy-pasted the body, but you're right. This is a less straightforward case because of the need to correlate tables and tableHeadings - I would probably refactor the DOM to keep those together, perhaps wrap in a DIV and then use the wrapper as the selector and loop var instead.

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.