Nested for-loop only executing once

前端 未结 2 1590
后悔当初
后悔当初 2021-01-28 08:26

I am using JavaScript and jQuery to create a simple 40x40 grid.

Here\'s my nested for loop to do this:

function display_grid() {
  browser_grid = \'\'
           


        
相关标签:
2条回答
  • 2021-01-28 09:04

    Thanks for the help guys!

    Changed the variable for my inner loop fixed the problem, but there was a problem with using .append()

    Apparently it doesn't support partial markup, so instead I just appended all of my divs to a string instead.

    for(var i=0;i<40;i++){
                browser_grid+='<div>';
                for(var x=0;x<40;x++){
                    browser_grid+="<div class='square'> </div>";
                }
                browser_grid+='</div>';
            }
    
            $visible_grid.append(browser_grid)
    

    After which, I appended the string to $visible_grid

    This seemed to do what I wanted it to do. Just wanted to point it out for anyone else using the append method for this purpose.

    0 讨论(0)
  • 2021-01-28 09:05

    You need a different variable name for the inner loop.

    function display_grid() {
        browser_grid='';
        $visible_grid = $('#grid');
    
        for(var i=0; i<40; i++){
            $visible_grid.append('<div>');
            for(var j=0; j<40; j++){
                $visible_grid.append("<div class='square'> </div>");
            }
            $visible_grid.append('</div>');
        }
    

    Edit: Added code. Note that you should use the var keyword for counting variables in your for-loops.

    What happened in your code is that after the 40 inner divs are created, the counter i is at 40 and the condition for the outer loop isn't true any longer, thus exiting that code block.

    0 讨论(0)
提交回复
热议问题