`for`循环中的`appendChild`只是替换`createElement`创建的项目 [英] `appendChild` inside a `for` loop just replaces item created by `createElement`

查看:279
本文介绍了`for`循环中的`appendChild`只是替换`createElement`创建的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了很多关于用 appendChild 创建多个项目,但我不理解它是如何工作的。我的 appendChild 只是替换而不是添加很多。

  var startGame; 
var cards = 16;
var newDeck = [];

startGame = function(){
var startBtn = document.getElementById('start');
var board = document.getElementById('game-board');
var backside = document.createElement(div);
backside.className ='card';

startBtn.onclick = function(){
removeButton = document.getElementById(start);
removeButton.parentNode.removeChild(removeButton);

for(var i = 0; i< cards; i ++){
board.appendChild(backside);
}
};
};

我也读过你可以用 innerHTML ,但这也让我感到困惑。有没有人有关于如何使这项工作更详细的解释? 解决方案

appendChild上的MDN
$ b


将节点添加到指定父元素
节点的子元素列表的末尾。如果节点已经存在,它会从当前父节点
节点中删除,然后添加到新的父节点中。

当您追加一个尚未在DOM中的元素,您将它从旧的地方移开。在循环中创建元素:

  startBtn.onclick = function(){
removeButton = document.getElementById(开始);
removeButton.parentNode.removeChild(removeButton);

for(var i = 0; i< cards; i ++){
var backside = document.createElement(div);
backside.className ='card';
board.appendChild(背面);
}
};


I Googled a lot about creating multiple items with appendChild, but I’m not understanding how it works. My appendChild just replaces instead of adding many.

var startGame;
var cards = 16;
var newDeck = [];

startGame = function(){
    var startBtn = document.getElementById('start');
    var board = document.getElementById('game-board');
    var backside = document.createElement("div");
    backside.className = 'card';

    startBtn.onclick = function(){
        removeButton = document.getElementById("start");
        removeButton.parentNode.removeChild(removeButton);

        for(var i = 0; i < cards; i++){ 
            board.appendChild(backside);
        }
    };
};

I also read you can do this with innerHTML, but that leaves me confused as well. Does anyone have a more detailed explanation on how to make this work?

解决方案

From the MDN on appendChild :

Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.

When you append an element that is yet in the DOM, you move it from its old place. Create the element in the loop :

startBtn.onclick = function(){
    removeButton = document.getElementById("start");
    removeButton.parentNode.removeChild(removeButton);

    for(var i = 0; i < cards; i++){ 
        var backside = document.createElement("div");
        backside.className = 'card';
        board.appendChild(backside);
    }
};

这篇关于`for`循环中的`appendChild`只是替换`createElement`创建的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆