如何使用JS将HTML卡片id作为路径变量通过URL传递到第二页并赋值
路径变量形式参数传递与读取实现方案
第一页:卡片点击跳转逻辑
1. 卡片HTML结构示例
给每个卡片绑定自定义属性存储id,避免直接写死URL,方便动态生成:
<div class="card" data-card-id="1">卡片1内容</div> <div class="card" data-card-id="2">卡片2内容</div> <div class="card" data-card-id="3">卡片3内容</div>
2. 跳转逻辑实现
原生JavaScript版本
// 监听所有卡片的点击事件 document.querySelectorAll('.card').forEach(card => { card.addEventListener('click', function() { // 获取当前卡片的id const cardId = this.dataset.cardId; // 拼接路径变量形式的URL跳转 window.location.href = `http://www.xyz.com/page2.html/${cardId}`; }); });
jQuery版本
$('.card').on('click', function() { const cardId = $(this).data('card-id'); window.location.href = `http://www.xyz.com/page2.html/${cardId}`; });
第二页:读取路径中的id参数
核心逻辑是从当前页面的URL路径中提取page2.html/后的片段,同时做异常兼容:
原生JavaScript实现
function getCardIdFromPath() { const path = window.location.pathname; // 匹配page2.html后的路径片段 const match = path.match(/\/page2\.html\/(\d+)/); // 匹配成功返回id,否则返回null或者默认值 return match ? match[1] : null; } // 调用方法获取id赋值给变量 const cardId = getCardIdFromPath(); // 后续可以根据业务逻辑处理cardId if(cardId) { console.log('获取到的卡片id:', cardId); } else { console.log('未获取到有效卡片id'); }
jQuery实现(逻辑和原生一致,仅语法差异)
function getCardIdFromPath() { const path = window.location.pathname; const match = path.match(/\/page2\.html\/(\d+)/); return match ? match[1] : null; } const cardId = getCardIdFromPath();
注意事项
静态服务器默认会将page2.html/2识别为目录下的文件请求,直接访问或刷新会返回404,需要提前配置服务端伪静态规则,将所有匹配^/page2.html/(\d+)的请求都转发到/page2.html即可,前端逻辑无需修改。
内容的提问来源于stack exchange,提问作者HelloCH
相关产品推荐
相关产品推荐

