You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面刷新后如何保留原有localStorage数据并启用新存储?

问题描述

当前分数递增及localStorage存储功能运行正常,分数会根据游戏胜负结果递增。但刷新页面后,页面显示的分数会重置为0,再次进行游戏时,会从初始值开始更新同一组localStorage数据。想要保留上次的localStorage数据不变,在页面刷新后启用新的存储来记录新的游戏分数。

现有代码
function gameWon() {
    if (animalStatus === answer) {
        let oldScore = parseInt(document.getElementById("win").innerText);
        document.getElementById("win").innerText = ++oldScore;
        document.getElementById("key-container").innerHTML = `Well done! That was correct!<br> <button id="play-again" onclick="playAgain()">Play again!</button>`;
        localStorage.setItem("wins", document.getElementById("win").innerText);
    }
};

function gameLost() {
    if (wrongGuess === 6) {
        let oldScore = parseInt(document.getElementById("loss").innerText);
        document.getElementById("loss").innerText = ++oldScore;
        document.getElementById("key-container").innerHTML = `Unfortunately you ran out of possible guesses.<br> Correct answer was: ${answer}!<br><button id="play-again" onclick="playAgain()">Play again!</button>`;
        localStorage.setItem("losses", document.getElementById("loss").innerText);
    }
};
解决方案

核心思路是用数组存储每一轮游戏的完整胜负数据,刷新页面后保留历史数组,同时初始化新游戏的分数为0,当前游戏结束后将结果追加到历史数组,不会覆盖原有数据。

步骤1:页面初始化逻辑

页面加载时读取历史记录,初始化当前游戏的分数:

document.addEventListener('DOMContentLoaded', function() {
    // 读取历史游戏记录,无数据则初始化空数组
    let gameHistory = JSON.parse(localStorage.getItem('gameHistory')) || [];
    // 当前游戏的胜负分数初始化为0
    let currentWins = 0;
    let currentLosses = 0;

    // 更新页面显示初始分数
    document.getElementById("win").innerText = currentWins;
    document.getElementById("loss").innerText = currentLosses;

    // 将变量挂载到全局,方便其他函数访问
    window.gameHistory = gameHistory;
    window.currentWins = currentWins;
    window.currentLosses = currentLosses;
});

步骤2:修改胜负函数逻辑

更新当前游戏分数,游戏结束时将结果追加到历史数组:

function gameWon() {
    if (animalStatus === answer) {
        window.currentWins++;
        document.getElementById("win").innerText = window.currentWins;
        document.getElementById("key-container").innerHTML = `Well done! That was correct!<br> <button id="play-again" onclick="playAgain()">Play again!</button>`;
        // 保存当前游戏结果到历史记录
        saveCurrentGameResult();
    }
};

function gameLost() {
    if (wrongGuess === 6) {
        window.currentLosses++;
        document.getElementById("loss").innerText = window.currentLosses;
        document.getElementById("key-container").innerHTML = `Unfortunately you ran out of possible guesses.<br> Correct answer was: ${answer}!<br><button id="play-again" onclick="playAgain()">Play again!</button>`;
        // 保存当前游戏结果到历史记录
        saveCurrentGameResult();
    }
};

// 封装保存逻辑,将当前游戏结果追加到历史数组
function saveCurrentGameResult() {
    window.gameHistory.push({
        wins: window.currentWins,
        losses: window.currentLosses,
        timestamp: new Date().toLocaleString() // 可选:添加时间戳,方便区分不同轮次
    });
    localStorage.setItem('gameHistory', JSON.stringify(window.gameHistory));
}

步骤3:重置新一轮游戏分数

点击“Play again”时,重置当前游戏的分数,准备新一轮记录:

function playAgain() {
    window.currentWins = 0;
    window.currentLosses = 0;
    document.getElementById("win").innerText = window.currentWins;
    document.getElementById("loss").innerText = window.currentLosses;
    // 这里需要补充重置游戏的其他状态,比如wrongGuess、animalStatus等,根据你的游戏逻辑调整
}

可选:展示历史游戏记录

如果需要查看之前的每轮成绩,可以添加以下代码渲染历史记录:

// 在页面初始化函数中添加
function renderGameHistory() {
    const historyContainer = document.createElement('div');
    historyContainer.innerHTML = '<h3>历史游戏记录</h3>';
    const historyList = document.createElement('ul');
    
    window.gameHistory.forEach((game, index) => {
        const listItem = document.createElement('li');
        listItem.textContent = `第${index+1}轮:胜利${game.wins}次,失败${game.losses}次 | ${game.timestamp}`;
        historyList.appendChild(listItem);
    });
    
    historyContainer.appendChild(historyList);
    document.body.appendChild(historyContainer);
}

// 在DOMContentLoaded事件中调用
renderGameHistory();

内容的提问来源于stack exchange,提问作者Darko Zlatarek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:15:33