如何实现跨HTML页面传递Javascript变量:速打游戏得分传递问题
ES6 模块的 import/export 仅支持同页面上下文内的模块数据共享,当你触发window.location.href跳转到新页面后,原游戏页面的所有JS运行上下文、内存数据都会被完全销毁,所以不可能通过模块导出导入的方式拿到跨页面的数据。
1. 修正游戏页逻辑+新增数据存储逻辑
1.1 修复跳转顺序BUG
原代码先执行页面跳转再调用算分函数,会导致算分逻辑还没执行就已经跳走,调整执行顺序:
// 原错误逻辑 if (bossHealth <= 0){ console.log("WORKING"); window.location.href = "./score.html"; createScore(); } // 修正后逻辑 if (bossHealth <= 0){ console.log("WORKING"); createScore(); // 先执行算分、存数据逻辑 window.location.href = "./score.html"; // 再跳转页面 }
1.2 修改createScore函数,将数据存入localStorage
删除无效的export语句,改用localStorage持久化存储需要传递的数据,同时补全缺失的变量声明:
// 先在代码开头添加缺失的变量声明:let timePoints; function createScore(){ let bonus = Math.floor(Math.random() * 500); score = timePoints * multiplier + bonus; // 存储所有需要传递到得分页的数据 localStorage.setItem('game_score', score); localStorage.setItem('game_time', scoreTime); localStorage.setItem('game_mistakes', mistakes); }
2. 修正得分页代码
2.1 修复HTML重复ID问题
原得分页三个展示数据的p标签用了相同的id,修改为唯一id:
<h3 id="time">TIME:</h3> <p id="timeVal"></p> <h3 id="score">SCORE:</h3> <p id="scoreVal"></p> <h3 id="mistakes">MISTAKES:</h3> <p id="mistakesVal"></p>
2.2 重写得分页JS逻辑
删除无效的import语句,从localStorage读取数据后渲染到页面,同时修正原有拼写错误:
const winMusic = new Audio(); winMusic.src = "./winmusic.mp3"; function celebrate(){ winMusic.play(); winMusic.loop = true; // 修正原拼写错误tru => true } // 读取本地存储的游戏数据 const gameScore = localStorage.getItem('game_score'); const gameTime = localStorage.getItem('game_time'); const gameMistakes = localStorage.getItem('game_mistakes'); // 渲染数据到页面 document.getElementById('scoreVal').textContent = `${gameScore} points!`; document.getElementById('timeVal').textContent = gameTime; document.getElementById('mistakesVal').textContent = gameMistakes;
可优化的小问题
- 游戏页HTML重复声明了两次
<!DOCTYPE html>,删除多余的一条即可 - 得分页引入的
gamescript.js完全无用,可以删掉对应script标签
内容的提问来源于stack exchange,提问作者Julian
相关产品推荐
相关产品推荐

