表单提交后用JS渲染Picross游戏页面(仅修改picross.js)
解决表单提交刷新问题并实现页面切换
核心思路
- 阻止表单默认提交行为,避免页面刷新
- 手动处理URL参数更新(用history API)
- 页面加载时检测URL参数,决定显示首页还是游戏界面
具体代码实现
1. 阻止表单提交刷新
在picross.js里添加表单提交事件监听,调用preventDefault()阻止默认行为:
// 监听表单提交事件 document.querySelector('form').addEventListener('submit', function(e) { // 阻止默认提交刷新 e.preventDefault(); // 获取表单数据,构造URL参数 const formData = new FormData(this); const params = new URLSearchParams(formData).toString(); // 更新URL参数(不刷新页面) history.pushState({ params }, '', `?${params}`); // 渲染游戏界面 renderGameInterface(); });
2. 页面加载时检测参数
页面初始化时检查URL是否有参数,决定显示内容:
document.addEventListener('DOMContentLoaded', function() { const urlParams = new URLSearchParams(window.location.search); if (urlParams.toString()) { // 有参数,隐藏首页,渲染游戏界面 document.querySelector('body > :not(.game-container)').style.display = 'none'; renderGameInterface(); } else { // 无参数,显示原首页 document.querySelector('.game-container')?.remove(); } });
3. 实现游戏界面渲染函数
写一个简单的renderGameInterface函数来生成网格(示例):
function renderGameInterface() { // 清除现有游戏内容(如果有) let gameContainer = document.querySelector('.game-container'); if (gameContainer) { gameContainer.remove(); } // 创建游戏容器 gameContainer = document.createElement('div'); gameContainer.className = 'game-container'; // 生成示例网格(比如5x5) for (let i = 0; i < 5; i++) { const row = document.createElement('div'); row.className = 'game-row'; for (let j = 0; j < 5; j++) { const cell = document.createElement('div'); cell.className = 'game-cell'; cell.addEventListener('click', function() { this.classList.toggle('filled'); }); row.appendChild(cell); } gameContainer.appendChild(row); } // 添加到页面 document.body.appendChild(gameContainer); }
4. 处理浏览器前进后退(可选)
监听popstate事件,确保后退时能正确切换页面:
window.addEventListener('popstate', function(e) { if (e.state?.params) { renderGameInterface(); } else { // 回到首页,显示原内容,移除游戏界面 document.querySelector('body > :not(.game-container)').style.display = ''; document.querySelector('.game-container')?.remove(); } });
关键说明
- 阻止默认提交:这是避免页面刷新的核心,
e.preventDefault()会取消浏览器的默认表单提交行为 - history API:
pushState可以在不刷新页面的情况下修改URL参数,让浏览器记录状态 - DOM操作:通过显示/隐藏原页面元素、动态创建游戏DOM来实现页面切换
内容的提问来源于stack exchange,提问作者Sozy
相关产品推荐
相关产品推荐

