动态元素里面的Javascript动态元素

时间:2014-04-02 09:22:07

标签: javascript dynamic elements

我尝试在动态创建的div中添加动态创建的元素(document.createElement('span'))。

这是我的代码:

// Newplayer div holder
var newPlayer = document.createElement('div');
newPlayer.setAttribute('id', 'player_' + playerID);
newPlayer.setAttribute('class', 'player_entry');
newPlayer.setAttribute('style', 'background-color: ' + getRandomColor());

// Points holder
var playerTotalPointsHolder = document.createElement('div');
playerTotalPointsHolder.setAttribute('id', 'player_' + playerID + "_total_holder");
playerTotalPointsHolder.setAttribute('class', 'player_total_holder');

var playerTotalPoints = document.createElement('span');
playerTotalPoints.setAttribute('id', 'player_' + playerID + "_total");
playerTotalPoints.setAttribute('class', 'player_total');
playerTotalPoints.innerHTML = 0;

// Put the pieces together
playerTotalPointsHolder.innerHTML = "Total: " + playerTotalPoints;

但输出是:

Playername [object HTMLDivElement]

所以我的问题是,如何在元素中插入元素?

4 个答案:

答案 0 :(得分:1)

playerTotalPointsHolder.innerHTML = "Total: ";
playerTotalPointsHolder.appendChild(playerTotalPoints);

答案 1 :(得分:0)

尝试更改此行:

playerTotalPointsHolder.innerHTML = "Total: " + playerTotalPoints;

到此:

playerTotalPointsHolder.appendChild(
  document.createTextNode('Total: ')
);
playerTotalPointsHolder.appendChild(
  playerTotalPoints
);

答案 2 :(得分:0)

您需要使用appendChild

// Setting total score...
playerTotalPoints.innerHTML = "Total: " + 0;

// And pushing `span` to `div`
playerTotalPointsHolder.appendChild(playerTotalPoints);

使用playerID 1,这将产生以下HTML:

<div id="player_1_total_holder" class="player_total_holder">
   <span id="player_1_total" class="player_total">Total: 0</span>
</div>

但是,我建议您不要使用span,而应使用p作为文字段落。但即便如此,同样的原则也适用于在元素内推送元素。

答案 3 :(得分:0)

您创建了元素,但是您没有将它们附加到DOM中的任何位置。在代码结束时,您需要执行以下操作:

playerTotalPointsHolder.appendChild(playerTotalPoints);
newPlayer.appendChild(playerTotalPointsHolder);
someDOMElementInYourDocument.appendChild(newPlayer);