Javascript 如何使用appendChild添加多个div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14910196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:17:56  来源:igfitidea点击:

How to add multiple divs with appendChild?

javascriptappendchild

提问by svtslvskl

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:

我正在尝试使用 javascript 制作棋盘并用它创建 64 个 div。
问题是,它只创建了第一个 div。
这是代码:

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>

采纳答案by T.J. Crowder

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

问题是,它只创建了第一个 div。

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

是的,因为您只创建了一个div. 如果要创建多个,则必须createElement多次调用。移动你的

d=document.createElement("div");

line intothe jloop.

所述j环。

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

如果你调用appendChild传入一个已经在 DOM 中的元素,它会被移动,而不是被复制。

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";
                }
            }
        }
    }

回答by Renato Zannon

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 appendChildin the DOM: by creating a documentFragment.

正如 tj-crowder 所指出的,OP 的代码只创建了一个 div。但是,对于谷歌人来说,有一种方法可以appendChild在 DOM 中使用单个元素附加多个元素:通过创建一个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

回答by magikMaker

Although what T.J. Crowder writes works fine, I would recommend rewriting it to the code below, using a documentFragment, like Renato Zannon suggested. That way you will only write to the DOM once.

尽管 TJ Crowder 编写的工作正常,但我建议将其重写为下面的代码,使用 documentFragment,就像 Renato Zannon 建议的那样。这样你只会写入一次 DOM。

    window.onload = function() {
        var count = 5,
            div,
            board = document.getElementById('board'),
            fragment = document.createDocumentFragment();
        
        // rows
        for (var i = 0; i < count; ++i) { 

            // columns
            for (var j = 0; j < count; ++j) { 
                div = document.createElement('div');
                div.className = (i % 2 != 0 && j % 2 == 0) || (i % 2 == 0 && j % 2 != 0) ? 'black' : 'white';
                fragment.appendChild(div);
            }
        }
        
        board.appendChild(fragment);
    };
#board {
  background-color: #ccc;
  height: 510px;
  padding: 1px;
  width: 510px;
}

.black,
.white {
    float: left;
    height: 100px;
    margin: 1px;
    width: 100px;
}

.black {
  background-color: #333;
}

.white {
  background-color: #efefef;
}
<div id="board"></div>

回答by Alexander V. Ulyanov

function crt_dv(){
dv=document.createElement('div'),document.body.appendChild(dv)
};

crt_dv(),dv.className='white';crt_dv(),dv.className='black';

Also use: for(i=0;i<2;i++)

也使用: for(i=0;i<2;i++)