替换/更新 HTML Canvas 游戏中的分数

Replace / Update Score in HTML Canvas Game

我希望分数随着连续 wins/fails 的增加而更新。

我知道 .append() 只是为了将对象附加到页面。但是我想不出如何用新乐谱替换内容,而不是不断追加新字符串。

我试过了.replace().replaceWith().replaceAll();将新分数设置为另一个变量并编写条件语句。我觉得我正在查看一些非常明显的东西,但无法弄清楚。谁能指出我正确的方向?

欢迎任何意见。谢谢!

var Player = function() {

    this.xRange = [-2, 402];
    this.yRange = [-20, 380];
    this.sprite = 'images/char-boy.png';
    this.wins = 0;
    this.fails = 0;
    this.reset();
};


Player.prototype.update = function() {

    if (this.y <= 20) {
        // player is on water, reset
        this.wins++;
        $("#wins").append("Wins: " + this.wins);
        this.reset();
    } else if (this.y <= 220 & this.x >= 0) {
        var charBoy = this;
        // player is on road rows, check collisions
        // loop through each bug
        allEnemies.forEach(function(enemy) {
            // is the bug on the same row as the player?
            if (enemy.y == charBoy.y) {
                // is the bug on the player?
                if (enemy.x >= charBoy.x - 30 && enemy.x <= charBoy.x + 30) {
                    charBoy.fails++;
                    $("#fails").append("Fails: " + charBoy.fails);
                    charBoy.reset();
                }
            }
        });
    }
};

如果您只用文本替换元素的内容,您可以使用 .text:

$("#fails").text("Fails: " + charBoy.fails);

如果要用html替换内容,可以用.html

$("#fails").html("Fails: " + charBoy.fails);