对象数组中的 html 表单搜索



我需要能够在对象数组中搜索。我有一个 HTML-for:

<form action="#" id="filters">
        <label for="search">Search</label>
        <input type="search" name="search" id="search"/>
    </form>
    <div id="searchresult"></div>

我不知道如何开始,有人可以帮助我吗?提前感谢!

有多种方法可以实现您要做的事情。

一种方法是将input事件附加到输入字段,以便每当输入字段值发生更改时,都可以获取输入字段值,然后使用筛选方法根据输入字段的值筛选meals数组。最后,您可以在searchresult div中显示过滤结果。

const meals = [
   {
     id: 1,
     title: 'Strawberry Salad with Poppy Seed Dressing',
     img: 'Strawberry-Salad-with-Poppy-Seed-Dressing.jpg',
     book: 1
   },
   {
     id: 2,
     title: 'Cashew Turkey Salad Sandwiches',
     img: 'turkey-sandwich.jpg',
     book: 2
   }
];
const searchField = document.querySelector('#search');
const searchResultsContainer = document.querySelector('#searchresult');
searchField.addEventListener('input', (e) => {
  
  // if input field is empty, clear the search results
  if(e.target.value === '') {
     searchResultsContainer.innerHTML = '';
     return;
  }
  
  // filter the meals array
  const searchResults = meals.filter(meal => {
      return meal.title.toLowerCase().includes(e.target.value.toLowerCase());
  });
  
  // before displaying the search results, clear the search results div
  searchResultsContainer.innerHTML = '';
  
  // display the titles of the meal objects that include the text entered in input field
  searchResults.forEach((element, index) => {
     const p = document.createElement('p');
     p.textContent = (index + 1) + '. ' + element.title;
     searchResultsContainer.appendChild(p);
  });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<form action="#" id="filters">
    <label for="search">Search</label>
    <input type="search" name="search" id="search"/>
</form>
<div id="searchresult"></div>
</body>
</html>

在不透露完整代码并说,你在这里,我将尝试导航你,以便你可以提出自己的解决方案。 大致遵循以下步骤:

  • 收听您的搜索输入 = 当您在键盘上键入您想要更新搜索结果。你可以听一下按键,向下键或简单的输入更改输入内的其他事件
  • 按下键时,您需要检查输入中的新值 = 您可以通过检查它的值属性来做到这一点。
  • 最后,您只想从列表中获取符合搜索值 = 有时尚的 JS 函数来过滤掉数组,或者您可以在标准 for 循环中执行此操作

希望这能让你对该怎么做有所了解。这可能是你的灵感来源

尝试使用array.filter(function(currentValue, index, arr), thisValue)

最新更新