1

I'm writing a logging function for automation unit test.

html elements structure:

<li> 
  <strong>
  <ol>
<li>
  <strong>
  <ol>

I want to make it when I click on the <strong>, the <ol> which under same <li> be toggle.

code:

for(var i = 0, l = logSuites.length; i < l; i++) {
        var suite = logSuites[i];
        $("#tests").append('<li><strong>....</strong></li>');
        var suiteSl = $('#tests > li:nth-child(' + (i + 1) + ')');
        var caseli = "<li>...</li>...";
        ...
        suiteSl.append('<ol style="display:none">' + caseli + '</ol>');
        var caseLiSl = suiteSl.children('ol');
        var toggleCases = function() {
            caseLiSl.toggle();
        };
        suiteSl.children('strong').bind('click', toggleCases);
    }

the problem is everytime the event being triggered, the last <ol> be toggled.. The variable caseLiSl in function toggleCases is always the last time it settled in the for loop

1
  • 1
    A common problem with the powerful javascript closures Commented Mar 26, 2012 at 10:57

3 Answers 3

7

That’s a more common problem. We use closures in a loop (for or while) and it always keep the last value of the increment.

Answer can be found in this question: Doesn't JavaScript support closures with local variables?

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

Comments

2

I think you should do

suiteSl.children('strong').bind('click', function(){
   $(this).children('ol').toggle();
});

in this way the this variable refers to the clicked element and you toggle only it's direct <ol> children

1 Comment

I may not be clear but <ol> isnot <strong> 's child but <li>'s. $(this).parent().children('ol').toggle(); works, thanks
2

This is again the usual closure in a loop problem.

You probably should read this: http://www.mennovanslooten.nl/blog/post/62

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.