简体   繁体   中英

Javascript updating textContent

I am having an issue with updating text content, if I select the element with document.querySelector() then it works but if I store the element in an object then I can't seem to update it.

Example:

let player1 = {
    totalScore: 0,
    currentScore: 0,
    totalScoreBox: document.querySelector('#score--0').textContent,
    currentScoreBox: document.querySelector('#current--0').textContent
}

const updatePlayerScore = (player, value) => {
    player.totalScore += value;
    player.currentScore += value;
    player.currentScoreBox = parseFloat(player.currentScore); //Doesn't work
    document.querySelector('#current--0').textContent = parseFloat(player.currentScore); //Works
}

https://jsfiddle.net/Copopops/rsuc7m4g/1/

Thanks in advance.

This line currentScoreBox: document.querySelector('#current--0').textContent retrieves the textContent as a string, and stores that string in the currentScoreBox variable. When you set currentScoreBox to another string, all you are doing at that point is replacing the value of that variable, it is in no way attached to your DOM.

Instead, store the node itself.

let player1 = {
    totalScore: 0,
    currentScore: 0,
    totalScoreBox: document.querySelector('#score--0'),
    currentScoreBox: document.querySelector('#current--0')
}

const updatePlayerScore = (player, value) => {
    player.totalScore += value;
    player.currentScore += value;
    player.currentScoreBox.textContent = parseFloat(player.currentScore);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM