如何通过Restful API响应数据为category变量赋值
问题根因
你之前的两种方案失效的原因分别是:
- DOM取值方案:你循环渲染4个商品,所有分类标签都用了同一个
id="categoryy",HTML规范要求id全局唯一,重复id会导致getElementById只能匹配到第一个元素;另外如果你的取值代码写在fetchProductDetail()调用之后,fetch是异步请求,执行取值代码时DOM还没渲染完成,自然拿不到值。 - 回调直接赋值方案:你在
map的迭代函数内用var定义category变量,这个变量的作用域仅局限于单次循环的迭代函数,外部无法访问,自然取不到值。
解决方案
按你的使用场景选择对应实现即可:
场景1:需要全局获取所有商品的分类值
在全局作用域定义变量存储分类列表,在fetch的回调里完成赋值,相关使用逻辑也需要放在异步回调内执行:
// 全局作用域定义分类存储变量 let allCategories = []; function fetchProductDetail() { fetch('https://something.com') .then(response => response.json()) .then(data => { // 提取所有商品分类赋值给全局变量 allCategories = data.map(product => product.Category_Name); // 所有需要用到分类值的逻辑都可以写在这里 console.log('所有商品分类:', allCategories); // 原有渲染逻辑保留,注意把重复id去掉,换成自定义属性区分 const html = data.map((product, index) => { return ` <div class="row"> <div class="column50"> <span class="discount">${product.Discount}</span> <img style="width: 300px; height: auto;" src="${product.Image}" alt=""> </div> <div class="column50" style="margin: 20px;"> <span class="category" data-product-index="${index}"> ${product.Category_Name} </span> <span class="dealer"> ${product.Suppliers_Name} </span> <br> <br> <div class="stars"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star-half-alt"></i> </div> <div class="price"> ${product.Final_Price} <span> ${product.Default_Price} </span> </div> <span style="padding:0 .7rem; font-size: 1.7rem;"> ${product.Description} </span> </div> </div> `; }).join(""); document.querySelector('#productDetails').insertAdjacentHTML("afterbegin", html); }) .catch(error => console.log(error)) } fetchProductDetail();
场景2:需要获取单个商品对应的分类
如果是要获取指定索引的商品分类,直接用allCategories[索引值]即可;如果是交互时(比如点击商品)获取对应分类,可以通过事件委托实现:
document.querySelector('#productDetails').addEventListener('click', (e) => { const targetRow = e.target.closest('.row'); if(targetRow) { const currentCategory = targetRow.querySelector('.category').textContent.trim(); // 拿到对应分类后执行你的逻辑即可 console.log('当前商品分类:', currentCategory); } })
内容的提问来源于stack exchange,提问作者Kleaaa
相关产品推荐
相关产品推荐

