如何在Pug表单中实现下拉框联动筛选功能?
实现方案
1. 后端接口开发(基于Node.js + MongoDB,示例用Express框架)
首先编写两个数据查询接口,分别用于获取对应分类下的品牌、对应分类+品牌下的产品:
// 按产品分类查询关联品牌列表 app.get('/api/get-brands', async (req, res) => { const { type } = req.query; // 此处的集合名、字段名替换为你自己MongoDB库中的实际命名 const brandList = await BrandModel.distinct('brand', { type: type }); res.json(brandList); }); // 按产品分类+品牌查询关联产品列表 app.get('/api/get-products', async (req, res) => { const { type, brand } = req.query; const query = { type: type }; if (brand) query.brand = brand; const productList = await ProductModel.distinct('product', query); res.json(productList); });
2. Pug模板改造
给三个下拉框加上ID标识,默认未选状态下将后续层级的下拉框设为禁用,你原本的循环渲染分类的逻辑可以保留:
form select#type(name="Type") option(value="") 请选择分类 //- 你原本的循环渲染所有分类的逻辑保持不变 select#brand(name="Brands" disabled) option(value="") 请先选择分类 select#product(name="Products" disabled) option(value="") 请先选择品牌
3. 前端交互逻辑
在模板底部插入原生JS代码,监听下拉框的选中变化事件,动态请求数据更新选项:
const typeSelect = document.getElementById('type'); const brandSelect = document.getElementById('brand'); const productSelect = document.getElementById('product'); // 监听分类下拉框变化 typeSelect.addEventListener('change', async () => { const selectedType = typeSelect.value; // 重置后续下拉框状态 brandSelect.innerHTML = '<option value="">请选择品牌</option>'; productSelect.innerHTML = '<option value="">请选择产品</option>'; productSelect.disabled = true; if (!selectedType) { brandSelect.disabled = true; return; } // 请求对应分类的品牌列表 const res = await fetch(`/api/get-brands?type=${encodeURIComponent(selectedType)}`); const brands = await res.json(); // 渲染品牌选项 brands.forEach(item => { const opt = document.createElement('option'); opt.value = item; opt.textContent = item; brandSelect.appendChild(opt); }); brandSelect.disabled = false; }); // 监听品牌下拉框变化 brandSelect.addEventListener('change', async () => { const selectedType = typeSelect.value; const selectedBrand = brandSelect.value; productSelect.innerHTML = '<option value="">请选择产品</option>'; if (!selectedBrand) { productSelect.disabled = true; return; } // 请求对应分类+品牌的产品列表 const res = await fetch(`/api/get-products?type=${encodeURIComponent(selectedType)}&brand=${encodeURIComponent(selectedBrand)}`); const products = await res.json(); // 渲染产品选项 products.forEach(item => { const opt = document.createElement('option'); opt.value = item; opt.textContent = item; productSelect.appendChild(opt); }); productSelect.disabled = false; });
补充说明
如果你的整体数据量很小,也可以在首次渲染页面时,把全量的分类-品牌-产品关联数据序列化为JSON注入到前端全局变量,直接在前端做过滤,不用每次触发选择都发请求,性能更好。
内容的提问来源于stack exchange,提问作者user16802669
相关产品推荐
相关产品推荐

