本文介绍了`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 ,但这也让我感到困惑。有没有人有关于如何使这项工作更详细的解释? 解决方案


$ 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 :

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`创建的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 08:46