如何实现选择vareKategori分类后仅展示对应分类商品的功能
分类筛选商品功能实现方案
方案1:前端直接过滤(快速实现,适合考试场景)
不需要修改后端代码,仅调整前端逻辑即可完成功能:
- 第一步:在JS代码最开头声明全局变量存储全量商品数据,避免重复请求接口:
let allGoods = []; - 第二步:修改
renderTable函数内的下拉框代码,添加筛选事件监听,同时修复原有label语法错误:
把原有的<label Varekategori:</label><select name="kategori" id="kategori">替换为:<label>Varekategori:</label> <select name="kategori" id="kategori" onchange="handleFilter(this.value)"> <!-- 可选新增全部选项,方便切回全量展示 --> <option value="all">全部</option> <option value="mad">Mad</option> <option value="drikkelse">Drikkelse</option> </select> - 第三步:新增前端筛选处理函数:
function handleFilter(selectedCategory) { let renderData = allGoods if (selectedCategory !== 'all') { // 按选中的分类过滤商品 renderData = allGoods.filter(item => item.vareKategori === selectedCategory) } renderTable(renderData) } - 第四步:修改
handleLoad函数,把拉取到的全量商品存入全局变量:async function handleLoad() { try { const goods = await getGoods() allGoods = goods // 存储全量商品用于后续筛选 renderTable(goods) } catch(err) { console.error(err) } }
方案2:后端接口过滤(更规范,适合数据量大的场景)
如果需要后端承担筛选逻辑,可以按如下步骤调整:
- 第一步:后端新增分类查询路由:
router.get("/getproducts/category/:cate", (req, res)=>{ const targetCate = req.params.cate; // 替换为你实际的数据库查询逻辑,筛选vareKategori等于目标分类的商品 const filtered = products.filter(item => item.vareKategori === targetCate) res.status(200).json(filtered); }); - 第二步:前端新增按分类拉取商品的方法:
async function getGoodsByCategory(category) { const res = await fetch(`http://localhost:8200/varer/getproducts/category/${category}`) return await res.json() } - 第三步:调整筛选函数调用后端接口:
async function handleFilter(selectedCategory) { try { const goods = selectedCategory === 'all' ? await getGoods() : await getGoodsByCategory(selectedCategory) renderTable(goods) } catch (err) { console.error(err) } }
现有代码修复建议
- 修复图片标签的语法错误:原代码里
<img src="${row.billede}" style="height:100px;width000px;">改为<img src="${row.billede}" style="height:100px;width:100px;"> - 编辑按钮的onclick属性当前是无效值,后续开发可以补充对应编辑逻辑
内容的提问来源于stack exchange,提问作者mikkel
相关产品推荐
相关产品推荐

