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

点击电商首页商品图片跳转详情页并加载对应商品信息的实现方法

现有代码核心问题

  • 你给proGallery传的this是<a>标签,不是内部的<img>元素,直接调用getAttribute("src")无法正确拿到商品图片路径
  • 首页执行的JS无法操作新跳转的page2页面DOM,页面跳转后原页面的JS运行上下文会直接销毁,你写的修改pics数组src的代码完全不会在详情页生效

修复后的实现方案

1. 首页(Page1)代码

HTML

<div class="cont">
    <a href="javascript:;" data-product-id="1" onclick="proGallery(this)"><img src="product-gallery/a.jpeg"></a>
    <a href="javascript:;" data-product-id="2" onclick="proGallery(this)"><img src="product-gallery/f.jpeg"></a>
    <!-- 后续新增商品只需要加对应a标签,改data-product-id值即可 -->
</div>

JS

function proGallery(x){
    // 取当前点击商品的唯一标识
    const productId = x.dataset.productId;
    // 带参数跳转到详情页
    window.location.href = `page2.html?productId=${productId}`;
}

2. 详情页(Page2)代码

不需要修改原有HTML结构,新增以下JS即可:

window.onload = function() {
    // 从跳转链接中取出商品ID
    const urlParams = new URLSearchParams(window.location.search);
    const currentProductId = urlParams.get('productId');
    const thumbs = document.querySelectorAll(".product-images img");
    const mainImg = document.querySelector(".result img");

    // 配置商品对应的图片组,后续新增商品直接加对应配置即可
    const productImgConfig = {
        "1": ["a.jpeg", "b.jpeg", "c.jpeg", "d.jpeg", "e.jpeg"],
        "2": ["f.jpeg", "g.jpeg", "h.jpeg", "i.jpeg", "j.jpeg"]
    }

    // 匹配到对应商品就加载图片
    if(productImgConfig[currentProductId]) {
        const currentImgs = productImgConfig[currentProductId];
        // 赋值缩略图
        currentImgs.forEach((imgName, index) => {
            thumbs[index].src = `product-gallery/${imgName}`;
        })
        // 默认第一个图作为主展示图
        mainImg.src = thumbs[0].src;

        // 可选:点击缩略图切换主展示图
        thumbs.forEach(thumb => {
            thumb.addEventListener('click', () => {
                mainImg.src = thumb.src;
            })
        })
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:06:03