原生JavaScript实现商品筛选功能主要涉及DOM操作、事件监听和数据过滤等基础概念。以下是详细解答:
以下是一个简单的商品筛选示例,包含价格区间和品牌两个筛选条件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商品筛选</title>
</head>
<body>
<div>
<label for="minPrice">最低价格:</label>
<input type="number" id="minPrice">
</div>
<div>
<label for="maxPrice">最高价格:</label>
<input type="number" id="maxPrice">
</div>
<div>
<label for="brand">品牌:</label>
<select id="brand">
<option value="">全部</option>
<option value="Apple">Apple</option>
<option value="Samsung">Samsung</option>
<option value="Sony">Sony</option>
</select>
</div>
<ul id="productList">
<!-- 商品列表将通过JavaScript动态生成 -->
</ul>
<script>
const products = [
{ name: 'iPhone 12', brand: 'Apple', price: 699 },
{ name: 'Galaxy S21', brand: 'Samsung', price: 799 },
{ name: 'Xperia 1 III', brand: 'Sony', price: 1199 },
// 更多商品...
];
function renderProducts(filteredProducts) {
const productList = document.getElementById('productList');
productList.innerHTML = '';
filteredProducts.forEach(product => {
const li = document.createElement('li');
li.textContent = `${product.name} - ${product.brand} - $${product.price}`;
productList.appendChild(li);
});
}
function filterProducts() {
const minPrice = parseFloat(document.getElementById('minPrice').value) || 0;
const maxPrice = parseFloat(document.getElementById('maxPrice').value) || Infinity;
const brand = document.getElementById('brand').value;
const filteredProducts = products.filter(product => {
return product.price >= minPrice && product.price <= maxPrice &&
(brand === '' || product.brand === brand);
});
renderProducts(filteredProducts);
}
document.getElementById('minPrice').addEventListener('input', filterProducts);
document.getElementById('maxPrice').addEventListener('input', filterProducts);
document.getElementById('brand').addEventListener('change', filterProducts);
// 初始渲染
renderProducts(products);
</script>
</body>
</html>
通过以上步骤和示例代码,可以实现一个基本的原生JavaScript商品筛选功能,并解决常见的实现问题。
领取专属 10元无门槛券
手把手带您无忧上云