You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击绑定函数实现products.html商品跳转detail.html展示对应详情咨询

现有代码问题梳理

  1. 变量名不匹配:开头声明的DOM节点变量是listShirts,末尾插入节点时用的是listaRemeras,会直接报未定义错误
  2. 点击事件传参错误:onclick="moreShirt(i)"里的i没有作为模板变量注入,实际触发时拿不到遍历的索引值
  3. 遍历逻辑优化:当前仅做DOM插入操作,没有用到map返回的新数组,用forEach遍历更符合语义

完整实现方案

第一步:修改products.html逻辑代码

const listShirts = document.getElementById('shirts')
// 此处为你的商品数组,每个元素自带唯一id属性
const shirts = [
  // 你的商品数据
]

// 定义点击跳转函数
function moreShirt(prodId) {
  // 方案1:通过URL参数传商品id,适用于数据量小、允许参数暴露的场景
  location.href = `detail.html?prodId=${prodId}`
  
  // 方案2:通过sessionStorage传完整商品数据,适用于数据量大、不想参数暴露的场景,二者选其一即可
  // const targetProd = shirts.find(item => item.id === prodId)
  // sessionStorage.setItem('currentProd', JSON.stringify(targetProd))
  // location.href = 'detail.html'
}

shirts.forEach((prod, i ) => {
    let card = document.createElement('div')
    card.classList.add('row')
    card.innerHTML = `
     <div class="col-sm-6 col-md-3" style="padding-top: 1.5rem;">
        <div class="card conLink" onclick="moreShirt(${prod.id})"  >
            <img src="${prod.img}" class="card-img-top welcome-imagen" alt="">
            <div class="card-body">
            <h5 class="card-title welcome-titulo" alt="">${prod.name}</h5>
            <span class="card-title welcome-precio" alt="" >$ ${prod.price}</span >
            <div>
                <div class="welcome-color1" style="display: inline-block;"></div>
                <div class="welcome-color2" style="display: inline-block;"></div>
                <div class="welcome-color3" style="display: inline-block;"></div>                                        
            </div>
            <div class="btn btn-primary welcome-vermas-producto"  >MORE INFO</div>
            </div>
                      
        </div>
    </div>`
  listShirts.appendChild(card)
})

第二步:在detail.html中接收参数渲染

如果用方案1的URL传参,使用以下逻辑:

// detail.html的JS代码
// 可在此处维护全量商品数组,或者调用后端接口查询对应id的商品数据
const shirts = [/* 全量商品数据 */]
// 提取URL中的商品id
const params = new URLSearchParams(location.search)
const currentProdId = params.get('prodId')
// 匹配对应商品
const currentProd = shirts.find(item => item.id == currentProdId)
// 将currentProd的属性值渲染到页面对应节点即可

如果用方案2的sessionStorage传参,使用以下逻辑:

const currentProd = JSON.parse(sessionStorage.getItem('currentProd'))
// 渲染到页面即可,渲染完成后可按需清除存储
// sessionStorage.removeItem('currentProd')

内容的提问来源于stack exchange,提问作者Hanna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:36:00