How to add multiple divs with appendChild?

前端 未结 4 556
挽巷
挽巷 2020-12-13 18:03

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:



        
4条回答
  •  我在风中等你
    2020-12-13 19:04

    The problem is, that it creates only the first div.

    Right, because you've only created one div. If you want to create more than one, you must call createElement more than once. Move your

    d=document.createElement("div");
    

    line into the j loop.

    If you call appendChild passing in an element that's already in the DOM, it's moved, not copied.

    window.onload=function()
        {
            var i=0;
            var j=0;
    
            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))
                    {
                        var d=document.createElement("div");
                        document.body.appendChild(d);
                        d.className="black";
                    }
                    else
                    {
                        var d=document.createElement("div");
                        document.body.appendChild(d);
                        d.className="white";
                    }
                }
            }
        }
    

提交回复
热议问题