js implements multi-condition filter list

You can implement a multi-condition filter list by following these steps:

  1. Create an array containing all list items.
  2. Create an empty array to store list items that match the filter criteria.
  3. Create an object containing all filter conditions, each corresponding to an input box or drop-down menu.
  4. Listen to the change event of each input box or drop-down menu, and update the value of the filter object when it changes.
  5. Iterate through the array of list items and, for each list item, check whether all filter conditions are met.
  6. If the list item matches all filter criteria, it is added to the array where the results are stored.
  7. Renders the list items in the resulting array.

Here is a simple implementation example:

// 列表项数组
const items = [
  { name: 'Apple', category: 'Fruit', price: 2.5 },
  { name: 'Banana', category: 'Fruit', price: 1.5 },
  { name: 'Carrot', category: 'Vegetable', price: 0.8 },
  { name: 'Tomato', category: 'Vegetable', price: 1.2 },
  { name: 'Orange', category: 'Fruit', price: 3.0 },
];

// 筛选条件对象
const filters = {
  name: '',
  category: '',
  price: '',
};

// 更新筛选条件对象的值
function updateFilter(key, value) {
  filters[key] = value;
  renderList();
}

// 检查是否符合筛选条件
function checkFilters(item) {
  for (let key in filters) {
    if (filters[key] !== '' && item[key] !== filters[key]) {
      return false;
    }
  }
  return true;
}

// 渲染列表
function renderList() {
  const filteredItems = items.filter(checkFilters);

  // 渲染筛选结果
  // ...
}

// 监听筛选条件输入框和下拉菜单的变化事件
document.getElementById('nameInput').addEventListener('change', (event) => {
  updateFilter('name', event.target.value);
});

document.getElementById('categorySelect').addEventListener('change', (event) => {
  updateFilter('category', event.target.value);
});

document.getElementById('priceInput').addEventListener('change', (event) => {
  updateFilter('price', event.target.value);
});

// 初始化列表
renderList();

In the above example, we created an array of list items containing product information and set three filter conditions, namely name, category and price. We update the value of the filter condition object by listening to the change events of the input box and drop-down menu, and re-render the list after each change to only display list items that meet all filter conditions.

Guess you like

Origin blog.csdn.net/song19990524/article/details/135024685