如何在javaScript对象中保存DOM元素?我想通过更新对象来更新页面。
Bellow我使用for循环创建并添加了网站元素。我想在一些对象属性中保存一些这些元素,这样我就可以通过更新对象中属性值的textContent来更新页面中的html。
for ( var i = 1 ; i <= numberOfPlayers ; i++ ){
//create object for each player.
var name = nameInputArray[i].value;
players["player" + i] = {
name: name,
score: 0,
fireStreak: 0,
xStreak: 0,
html: {}
}
//Create a Player box for each player.
var playerBox= document.createElement('div');
playerBox.classList.add('player_box');
document.getElementById('player-box-container').appendChild(playerBox);
var playerName = document.createElement('div');
playerName.textContent = players["player" + i].name;
playerName.classList.add('player_names');
playerBox.appendChild(playerName);
var playerScoreHeading = document.createElement('div');
playerScoreHeading.classList.add('player_score_heading');
playerScoreHeading.textContent = "Player Score:";
playerBox.appendChild(playerScoreHeading);
var playerScoreDiv = document.createElement('div');
playerScoreDiv.classList.add('player_score');
playerBox.appendChild(playerScoreDiv);
var playerScoreNumber = document.createElement('span');
playerScoreNumber.classList.add('player_score_number');
playerScoreNumber.textContent = players["player" + i].score;
playerScoreNumber.id = "player_score_number_" + i;
playerScoreDiv.appendChild(playerScoreNumber);
//THIS IS THE PART NOT WORKING!!!!!!!!!!!!!!!!!(THE NEXT LINE)
players["player" + i].html.score = document.getElementById("player_score_number_" + i);
playerScoreDiv.innerHTML += "pts";
}
出于某种原因,当我尝试访问时:
function changeScore(){
players.player1.html.score.textContent = 30;
}
它会改变对象内部,但不会在网页上呈现。
请帮忙。
答案 0 :(得分:1)
通过将HTML字符串重新分配给playerScoreDiv.innerHTML
,您将失去先前作为playerScoreDiv
的后代创建的所有元素对象:它们将从HTML中重新创建(具有明显不同的对象引用)。< / p>
所以而不是:
playerScoreDiv.innerHTML += "pts";
做的:
playerScoreDiv.appendChild(document.createTextNode('pts'));