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

ThemeZ
  • 473
  • 1
  • 5
  • 15

3 Answers3

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?

Community
  • 1
  • 1
antonjs
  • 14,060
  • 14
  • 65
  • 91
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

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • I may not be clear but
      isnot 's child but
    1. 's. `$(this).parent().children('ol').toggle();` works, thanks
    – ThemeZ Mar 26 '12 at 11:09
2

This is again the usual closure in a loop problem.

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

Jani Hartikainen
  • 42,745
  • 10
  • 68
  • 86