简体   繁体   中英

Creating Objects and Appending Them to Dynamically Created Objects

I've been searching around Google for a while and can't seem to find an answer to this issue of mine. I'm also somewhat new to js, so there's probably an easier way or something obvious I'm missing. Here's what I'm doing:

I want to create nine divs, and then put nine divs into each of those original nine. I have the following function:

function createDivs() {
       for(i = 0; i < 9; ++i) {
             var bigSquare = document.createElement("div");
             document.body.appendChild(bigSquare);
             bigSquare.className = "square";
             for(i = 0; i < 9; ++i) {
                 var smallSquare = document.createElement("div");
                 smallSquare.className = "pixel";
                 bigSquare.appendChild(smallSquare);
             }
       }
}

I thought this would create 9 groupings of 9 divs, those groupings being labeled under the class name "square" and the divs within each grouping being labeled with class name "pixel", but this isn't the case. Only one "bigSquare" div (containing nine "pixel" divs) is created instead of the nine that I want. I feel as if the creation of each new "bigSquare" div is simply replacing the previous one with each iteration of the loop, but I'm not sure. And it that was the case, I'm not sure how to work around it...any help? The way I've attempted to describe this is probably quite confusing :/

The problem is that you re-used the loop iteration variable i for both your outer and inner loops. Change one of them to j or something else, and your code should work.

You need to declare and change your variable per each loop, or else that initial variable i will just change when youre in the inside loop. Do it something like this:

function createDivs() {
    for (var i = 0; i < 9; i++) {
        var bigSquare = document.createElement("div");
        document.body.appendChild(bigSquare);
        bigSquare.className = "square";
        for (var k = 0; k < 9; k++) {
            var smallSquare = document.createElement("div");
            smallSquare.className = "pixel";
            bigSquare.appendChild(smallSquare);
        }
    }
}

Whoops. You are reusing "i" inside and "i" loop. Switch variables!

 function createDivs() { for(var i = 0; i < 9; ++i) { var bigSquare = document.createElement("div"); document.body.appendChild(bigSquare); bigSquare.className = "square"; for(var j = 0; j < 9; ++j) { var smallSquare = document.createElement("div"); smallSquare.className = "pixel"; bigSquare.appendChild(smallSquare); } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM