gpt4 book ai didi

javascript - 如何在 javaScript 对象中保存 DOM 元素?我想通过更新对象来更新页面

转载 作者:太空宇宙 更新时间:2023-11-04 08:52:04 24 4
gpt4 key购买 nike

如何在 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'));

关于javascript - 如何在 javaScript 对象中保存 DOM 元素?我想通过更新对象来更新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43359988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com