我有一个简单的HTML页面

javascript - 无法从回调中更新<span>的textContent(已分配给变量)-LMLPHP

当我按下“播放器1”和“播放器2”按钮时,我希望更改反映在页面上。在控制台得分上升时,一切都很好,但是为什么页面不更新更改的得分? (let p1scorelet p2score

这是我的代码,谢谢!

const p1button = document
    .querySelector('#p1')
    .addEventListener('click', scoreUp);
const p2button = document
    .querySelector('#p2')
    .addEventListener('click', scoreUp);

let p2score = document.querySelector('#p2score').textContent;
let p1score = document.querySelector('#p1score').textContent;

function scoreUp(e) {
    if (e.target.textContent === 'Player 1') {
        p1score++;
        console.log(p1score);
    } else {
        p2score++;
        console.log(p2score);
    }
}

最佳答案

当您执行let p1score = document.querySelector('#p1score').textContent;时,实际上是在保存文本内容的值,而不是对该值的引用。因此,p1scorep2score拥有它们自己的文本内容值(整数)的唯一副本。

因此,当您增加p1scorep2score时,您只会增加这些变量所持有的值。因此,增加值后,应通过执行以下操作将文本内容设置为增加的值

pScoreOneElem.textContent = p1score;

pScoreTwoElem.textContent = p2score;

通过更改其值以反映对p1scorep2score的更改,这将有效地更新文本内容:


const p1button = document
    .querySelector('#p1')
    .addEventListener('click', scoreUp);
const p2button = document
    .querySelector('#p2')
    .addEventListener('click', scoreUp);

let pScoreOneElem = document.querySelector('#p1score');
let pScoreTwoElem = document.querySelector('#p2score');

let p2score = pScoreTwoElem.textContent;
let p1score = pScoreOneElem.textContent;

function scoreUp(e) {
    if (e.target.textContent === 'Player 1') {
        p1score++;
        pScoreOneElem.textContent = p1score;
        console.log(p1score);
    } else {
        p2score++;
        pScoreTwoElem.textContent = p2score;
        console.log(p2score);
    }
}

<button id="p1">Player 1</button>
<button id="p2">Player 2</button>

<br />
<div class="player-scores">
  Player 1 Score: <span id="p1score">0</span>
  <br />
  Player 2 Score: <span id="p2score">0</span>
</div>

09-30 22:43