点击按钮显示产品详情:隐藏产品列表Div并渲染指定字段
实现方案
直接修改原代码即可,核心是给每个详情按钮绑定点击事件并关联对应产品数据,点击后切换容器显示状态并渲染详情:
// 确保HTML结构放在<body>标签内 // <div class="prod"></div> // <div class="details" style="display: none;"></div> const productContainer = document.querySelector(".prod"); const detailsContainer = document.querySelector(".details"); var ourRequest = new XMLHttpRequest(); ourRequest.open('GET','http://inec.sg/assignment/retrieve_records.php'); ourRequest.onload = function(){ var data = JSON.parse(ourRequest.responseText); renderProductList(data.songs); }; ourRequest.send(); // 渲染产品列表 function renderProductList(songs){ let html = ''; // 用let避免循环变量共享导致的索引错误 for(let i = 0; i < songs.length; i++){ const song = songs[i]; html += ` <div class="product-item"> <div><img src="${song.image}" height="200px"></div> <div><h2>${song.name}</h2></div> <div><h2>$${song.price}</h2></div> <button class="detail-btn" data-index="${i}">Details</button> </div> `; } productContainer.innerHTML = html; // 给所有详情按钮绑定点击事件 document.querySelectorAll('.detail-btn').forEach(btn => { btn.addEventListener('click', function(){ const index = this.dataset.index; showProductDetails(songs[index]); }); }); } // 显示产品详情 function showProductDetails(product){ // 隐藏产品列表,显示详情容器 productContainer.style.display = 'none'; detailsContainer.style.display = 'block'; // 渲染详情内容,添加返回按钮方便回到列表 detailsContainer.innerHTML = ` <button class="back-btn">返回列表</button> <div class="product-detail"> <img src="${product.image}" height="300px"> <h3>品牌: ${product.brand}</h3> <p>风格: ${product.style}</p> <p>折扣: ${product.discount}</p> <p>价格: $${product.price}</p> </div> `; // 绑定返回按钮事件 document.querySelector('.back-btn').addEventListener('click', function(){ productContainer.style.display = 'block'; detailsContainer.style.display = 'none'; }); }
关键改动说明:
- 给每个详情按钮添加
data-index属性,存储对应产品在数组中的索引,点击时可直接获取对应数据 - 将循环内的
var改为let,避免循环变量共享导致的索引错误 - 拆分出
renderProductList和showProductDetails函数,逻辑更清晰 - 初始给
.details容器设置display: none,默认隐藏详情区域 - 新增返回按钮,提升用户操作体验
- 采用一次性拼接HTML再赋值的方式,比循环内多次
innerHTML +=性能更优
内容的提问来源于stack exchange,提问作者Jack Lew
相关产品推荐
相关产品推荐

