You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript基于本地数据与用户文本输入实现列表过滤?

实现本地数据的文本输入过滤功能

嘿,我来帮你把这个本地产品数据的文本过滤功能给完善好!你已经有了基础的本地数据和初步的键盘事件判断思路,接下来咱们把功能补全,让它真正能用起来,而且体验还不错。

第一步:准备HTML结构

首先得有个输入框让用户输入关键词,还有个容器用来展示过滤后的产品列表:

<input type="text" id="searchInput" placeholder="搜索产品名称/类型...">
<div id="productList"></div>

第二步:完善JS逻辑

我把你的本地数据整合进去,然后补全过滤和渲染的逻辑,比单纯监听回车更灵活:

// 你的本地产品数据
var userData = { 
  "product": [ 
    { 
      "name":"cannon", 
      "type":"camera", 
      "serialno":"c123", 
      "stock":10, 
      "img":"http://placehold.it/400x250/000/fff", 
      "Description":"blablabla" 
    }, 
    { 
      "name":"cannon2", 
      "type":"camera2", 
      "serialno":"c124", 
      "stock":1, 
      "img":"http://placehold.it/400x250/fff/000", 
      "Description":"blablabla" 
    } 
  ] 
};

// 获取页面上的DOM元素
const searchInput = document.getElementById('searchInput');
const productList = document.getElementById('productList');

// 封装渲染产品列表的函数,方便重复调用
function renderProducts(products) {
  // 先清空现有列表,避免重复渲染
  productList.innerHTML = '';
  
  // 遍历产品数据,创建每个产品的卡片
  products.forEach(product => {
    const productCard = document.createElement('div');
    productCard.className = 'product-card';
    productCard.innerHTML = `
      <img src="${product.img}" alt="${product.name}">
      <h3>${product.name}</h3>
      <p>类型: ${product.type}</p>
      <p>库存: ${product.stock}</p>
      <p>${product.Description}</p>
    `;
    productList.appendChild(productCard);
  });
}

// 页面加载时先渲染所有产品
renderProducts(userData.product);

// 监听输入框的输入事件(比只监听keyCode更全面,支持粘贴、输入法等场景)
searchInput.addEventListener('input', function(e) {
  // 把搜索词转成小写并去除首尾空格,实现不区分大小写的模糊匹配
  const searchTerm = e.target.value.toLowerCase().trim();
  
  // 如果用户清空输入,就重新显示所有产品
  if (!searchTerm) {
    renderProducts(userData.product);
    return;
  }
  
  // 过滤产品:这里匹配了名称和类型,你可以根据需求添加更多字段(比如序列号、描述)
  const filteredProducts = userData.product.filter(product => {
    return product.name.toLowerCase().includes(searchTerm) || 
           product.type.toLowerCase().includes(searchTerm);
  });
  
  // 渲染过滤后的结果
  renderProducts(filteredProducts);
});

第三步:加一点基础样式(可选)

给产品卡片加些简单的样式,让页面看起来更舒服:

.product-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 16px;
  margin: 12px 0;
  max-width: 400px;
}
.product-card img {
  width: 100%;
  border-radius: 4px;
  margin-bottom: 12px;
}
.product-card h3 {
  margin-top: 0;
}

关键细节说明

  • 为什么用input事件而不是只监听键盘按键?因为它能捕获所有输入变化,比如用户用鼠标粘贴文本、用手写输入法输入,都能触发过滤,体验更流畅。
  • 不区分大小写的匹配:把搜索词和产品的字段都转成小写,这样用户输入"CANNON"也能匹配到"cannon",更友好。
  • 灵活的过滤逻辑:你可以在filter函数里添加更多判断条件,比如匹配序列号serialno或者描述Description,只要扩展返回的条件就行。

内容的提问来源于stack exchange,提问作者Arul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:42:47