我用Google浏览了很多关于使用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做到这一点,但这让我感到困惑.有没有人对如何使这项工作有更详细的解释?
解决方法:
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.
当您附加一个尚在DOM中的元素时,您将其从旧位置移动.在循环中创建元素:
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);
}
};