如何将index.html按钮ID传递到payment.html?点击按钮无响应
解决按钮ID跨页面传递失效问题
你的代码核心问题是按钮元素不能同时设置两个onclick属性,HTML解析时只会保留最后一个,导致pay(this.id)根本没被执行,localStorage里没存到ID值,跳转后payment.html自然拿不到数据。
下面提供两种可行的解决方案:
方案一:合并函数操作(基于localStorage)
把存储ID和页面跳转的逻辑合并到同一个函数里,确保存储动作先执行:
<!-- index.html --> <script> function pay(id) { localStorage.setItem('thing', id); // 用规范的setItem方法存储数据 window.location.href = 'payment.html'; } </script> <button type="button" id="opt1" onclick="pay(this.id)"></button>
payment.html的代码可以优化为更规范的写法:
<!-- payment.html --> <script> window.onload = function() { const cardElement = document.getElementById('card'); const savedId = localStorage.getItem('thing'); if (savedId) { cardElement.innerHTML = savedId; // 可选:用完后清除本地存储,避免数据残留 localStorage.removeItem('thing'); } else { cardElement.innerHTML = '未获取到ID'; } }; </script> <h1 id="card"></h1>
方案二:使用URL参数传递(无需依赖localStorage)
这种方式更直接,不需要借助本地存储,把ID拼到跳转URL中:
<!-- index.html --> <script> function pay(id) { window.location.href = `payment.html?id=${id}`; } </script> <button type="button" id="opt1" onclick="pay(this.id)"></button>
payment.html中解析URL参数获取ID:
<!-- payment.html --> <script> window.onload = function() { const cardElement = document.getElementById('card'); // 解析URL中的查询参数 const urlParams = new URLSearchParams(window.location.search); const id = urlParams.get('id'); if (id) { cardElement.innerHTML = id; } else { cardElement.innerHTML = '未获取到ID'; } }; </script> <h1 id="card"></h1>
内容的提问来源于stack exchange,提问作者if_statement
相关产品推荐
相关产品推荐

