Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - How to add multiple divs with appendChild?

I am trying to make a chessboard using javascript and creating 64 divs with it.
The problem is, that it creates only the first div.
Here is the code:

div {
    width: 50px;
    height: 50px;

    display: block;
    position: relative;
    float: left;
}

<script type="text/javascript">
    window.onload=function()
    {
        var i=0;
        var j=0;
        var d=document.createElement("div");

        for (i=1; i<=8; i++)
        {
            for (j=1; j<=8; j++)
            {
                if ((i%2!=0 && j%2==0)||(i%2==0 && j%2!=0))
                {
                    document.body.appendChild(d);
                    d.className="black";
                }
                else
                {
                    document.body.appendChild(d);
                    d.className="white";
                }
            }
        }
    }
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As t-j-crowder has noted, the OP's code only creates one div. But, for googlers, there is one way to append multiple elements with a single appendChild in the DOM: by creating a documentFragment.

function createDiv(text) {
  var div = document.createElement("div");
  div.appendChild(document.createTextNode(text));
  return div;
}

var divs = [
  createDiv("foo"),
  createDiv("bar"),
  createDiv("baz")
];

var docFrag = document.createDocumentFragment();
for(var i = 0; i < divs.length; i++) {
  docFrag.appendChild(divs[i]); // Note that this does NOT go to the DOM
}

document.body.appendChild(docFrag); // Appends all divs at once

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...