从数据到界面 用JavaScript动态生成一个可筛选和排序的商品列表页面

数据准备

准备一个包含商品信息的数组,每个商品对象包含名称、价格、类别等属性。示例数据如下:

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);
});

功能扩展

考虑添加更多功能点:

  • 多条件筛选(价格范围、品牌等)
  • 分页加载
  • 搜索框实现名称搜索
  • 本地存储保存用户偏好
  • 响应式设计适配移动设备
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值