如何在 javaScript 对象中保存 DOM 元素?我想通过更新对象来更新页面。
下面我使用 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;
}
它会改变对象内部,但不会在网页上呈现。
请帮忙。
通过将 HTML 字符串重新分配给 playerScoreDiv.innerHTML
,您将丢失之前作为 playerScoreDiv
的后代创建的所有元素对象:它们被重新创建(具有明显不同对象引用)来自 HTML。
所以代替:
playerScoreDiv.innerHTML += "pts";
做:
playerScoreDiv.appendChild(document.createTextNode('pts'));
我是一名优秀的程序员,十分优秀!