数据准备
准备一个包含商品信息的数组,每个商品对象包含名称、价格、类别等属性。示例数据如下:
const products = [
{ id: 1, name: 'Laptop', price: 999, category: 'Electronics' },
{ id: 2, name: 'Smartphone', price: 699, category: 'Electronics' },
{ id: 3, name: 'Headphones', price: 199, category: 'Electronics' },
{ id: 4, name: 'T-shirt', price: 19, category: 'Clothing' },
{ id: 5, name: 'Jeans', price: 49, category: 'Clothing' }
];
页面结构
创建基本的HTML结构,包含商品列表容器、筛选下拉框和排序按钮:
<div class="container">
<div class="controls">
<select id="categoryFilter">
<option value="all">All Categories</option>
<option value="Electronics">Electronics</option>
<option value="Clothing">Clothing</option>
</select>
<button id="sortPrice">Sort by Price</button>
</div>
<div id="productList"></div>
</div>
渲染商品列表
编写函数动态生成商品列表HTML:
function renderProducts(productsToRender) {
const productList = document.getElementById('productList');
productList.innerHTML = productsToRender.map(product => `
<div class="product">
<h3>${product.name}</h3>
<p>Price: $${product.price}</p>
<p>Category: ${product.category}</p>
</div>
`).join('');
}
实现筛选功能
为类别筛选器添加事件监听器:
document.getElementById('categoryFilter').addEventListener('change', (e) => {
const category = e.target.value;
const filteredProducts = category === 'all'
? products
: products.filter(product => product.category === category);
renderProducts(filteredProducts);
});
实现排序功能
为价格排序按钮添加事件监听器:
let ascending = true;
document.getElementById('sortPrice').addEventListener('click', () => {
const sortedProducts = [...products].sort((a, b) =>
ascending ? a.price - b.price : b.price - a.price
);
ascending = !ascending;
renderProducts(sortedProducts);
});
样式优化
添加基本CSS样式提升用户体验:
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.controls {
margin-bottom: 20px;
display: flex;
gap: 10px;
}
.product {
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 10px;
border-radius: 5px;
}
初始化页面
在页面加载时首次渲染商品列表:
document.addEventListener('DOMContentLoaded', () => {
renderProducts(products);
});
功能扩展
考虑添加更多功能点:
- 多条件筛选(价格范围、品牌等)
- 分页加载
- 搜索框实现名称搜索
- 本地存储保存用户偏好
- 响应式设计适配移动设备

被折叠的 条评论
为什么被折叠?



