点击HTML按钮后如何在另一页面动态加载赛事数据?
问题分析与解决方案
核心问题
- 跳转时机错误:点击按钮后立刻执行
document.location.href = "/quiz.html",页面会立即刷新跳转,当前页面的API请求和后续的updateQuizMatchData调用还没完成就被终止——因为页面环境已经销毁。 - 函数作用域不匹配:
updateQuizMatchData是在index.html的JS环境中定义的,跳转到quiz.html后,这个函数不存在于新页面的JS环境中,就算API请求侥幸完成,也无法调用它更新quiz.html的内容。
修正步骤
1. 修改index页面的点击事件代码
只负责存储赛事ID到localStorage,然后直接跳转,不要在当前页面处理API请求和页面更新:
const matchButton = document.querySelectorAll(".match-button"); for (let i = 0; i < matchButton.length; i++) { matchButton[i].addEventListener("click", (e) => { localStorage.setItem("matchID", e.target.id); document.location.href = "/quiz.html"; }); }
2. 在quiz页面实现数据加载与更新逻辑
在quiz.html对应的JS文件中,监听页面加载事件,读取localStorage中的赛事ID,请求API并更新页面:
// 确保stats对象在quiz页面可访问(比如通过公共JS文件引入) document.addEventListener('DOMContentLoaded', () => { const matchID = localStorage.getItem('matchID'); // 无赛事ID时跳回首页或提示 if (!matchID) { document.location.href = '/index.html'; return; } // 请求赛事数据并更新页面 stats.getFixture(matchID) .then((fixtureData) => { updateQuizMatchData(fixtureData); // 可选:用完后清除localStorage中的ID localStorage.removeItem('matchID'); }) .catch((err) => { console.error('获取赛事数据失败:', err); }); }); // 将updateQuizMatchData函数移到quiz页面的JS中 const updateQuizMatchData = (fixtureData) => { console.log(fixtureData); // 格式化真实赛事日期(替换原固定日期) const date = new Date(fixtureData.fixture.date).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-'); // 确保quiz页面存在.teams元素 const teams = document.querySelector('.teams'); if (!teams) return; teams.innerHTML = ` <div class="home-team m-4 pl-6"> <img class="team-badge w-40 h-40" src="${fixtureData.teams.home.logo}" alt="home-team" /> <p class="home-score text-center text-6xl m-6 bg-red-500 rounded-lg text-white p-6 shadow-xl" > ${fixtureData.goals.home ?? 0} </p> </div> <div class="vs-text pt-20"> <p class="text-center text-6xl font-extrabold p-4">VS</p> <p class="location text-center">${fixtureData.fixture.venue.name}</p> <p class="date text-center">${date}</p> </div> <div class="away-team m-4 pr-6"> <img class="team-badge w-40 h-40" src="${fixtureData.teams.away.logo}" alt="away-team" /> <p class="away-score text-center text-6xl m-6 bg-lime-500 rounded-lg text-white p-6 shadow-xl" > ${fixtureData.goals.away ?? 0} </p> </div> `; };
额外注意事项
- 确保
stats对象的API封装代码放在公共JS文件中,在index.html和quiz.html都引入,保证跨页面可访问。 - 检查
quiz.html中是否存在.teams元素,否则updateQuizMatchData无法找到目标元素更新内容。 - 用
${fixtureData.goals.home ?? 0}处理数据为空的情况,避免页面显示undefined。 - 可选:在获取到赛事数据后清除localStorage中的
matchID,防止用户刷新页面时重复加载旧数据。
内容的提问来源于stack exchange,提问作者OrcaDrive
相关产品推荐
相关产品推荐

