点击订单按钮Local Storage存储失效且window.location.href.replace跳转失败求助
问题修复方案
核心根因:DOMContentLoaded事件名拼写错误
你代码中绑定逻辑的事件名写为了DOMcontentLoaded,标准事件名应为DOMContentLoaded(D、C、L三个字母均为大写),拼写错误导致该事件回调完全没有执行,因此负责存储LocalStorage、页面跳转的点击事件根本没有绑定到按钮上。
你单独写在全局的点击日志监听是直接执行绑定的,页面加载完成后按钮已经渲染完毕,所以点击时能正常打印日志,但不会触发存储和跳转逻辑,这就是你遇到的现象的核心原因。
次要问题1:类名大小写不兼容
第一个商品的描述p标签类名为大写开头的Desc,第二个为小写开头的desc,你代码中统一用.desc选择器读取,点击第一个商品的按钮时会抛出找不到元素的错误,打断后续逻辑执行。
次要问题2:跳转逻辑适用性差
你使用window.location.href.replace("grc.html","order.html")的替换逻辑仅在当前页面文件名恰好是grc.html时生效,若live server打开的默认文件名不符、或者访问路径带其他后缀,替换操作不会生效,导致跳转失败。
修复后的完整JS代码
window.addEventListener("DOMContentLoaded", function(e){ const orderButtons= document.querySelectorAll("button[data-order]"); orderButtons.forEach(function(button){ button.addEventListener("click",function(e){ const button= e.currentTarget; const container= button.parentNode; // 兼容大小写类名,避免读取报错 const descElement = container.querySelector(".desc") || container.querySelector(".Desc"); const order={ id: button.getAttribute("data-order"), title: container.querySelector(".title").innerText, price1: container.querySelector(".Price").innerText, desc: descElement.innerText }; localStorage.setItem('order', JSON.stringify(order)); // 直接基于当前域名拼接order.html路径,不依赖原页面文件名 const url = new URL("/order.html", window.location.origin); window.location.href = url.href; }); }); console.log("The page is loaded."); }); // 原有重复的日志点击监听可以删除,避免重复绑定事件
order.html交互说明
order.html需要单独编写JS代码读取LocalStorage中存储的订单数据,才能实现后续的订单展示逻辑,示例代码如下:
window.addEventListener("DOMContentLoaded", function(){ const orderRaw = localStorage.getItem('order'); if(orderRaw) { const orderData = JSON.parse(orderRaw); // 此处补充你的订单数据渲染逻辑,将orderData的字段插入到页面对应位置即可 console.log('读取到订单数据:', orderData); } else { // 无订单数据的兜底逻辑,例如跳转回商品页 alert('未查询到有效订单信息'); window.location.href = '/'; } })
内容的提问来源于stack exchange,提问作者MOON CREED
相关产品推荐
相关产品推荐

