2017-04-12 82 views
0

如何保存一個javaScript對象內的DOM元素?我想通過更新對象來更新頁面。如何保存一個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; 
} 

它會改變物體內,但它不會對網頁渲染。

請幫忙。

+1

不要使用'.innerHTML + = ...'更新您的容器元素,因爲它會重新裏面的元素容器並打破您的參考。 – nnnnnn

回答

1

通過將一個HTML字符串重新分配給playerScoreDiv.innerHTML,您將失去先前創建的所有元素對象作爲playerScoreDiv的後代:它們將從HTML重新創建(具有明顯不同的對象引用)。

所以不是:

playerScoreDiv.innerHTML += "pts"; 

做:

playerScoreDiv.appendChild(document.createTextNode('pts')); 
+0

非常感謝!!!!!!!!它現在完美運行!太感謝了。 – Osuriel

相關問題