javascript - 对象数组中的html表单搜索

标签 javascript html arrays

<分区>

我需要能够在对象数组中进行搜索。 我有一个 HTML 用于:

<form action="#" id="filters">

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

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

最佳答案

有不止一种方法可以实现您想要做的事情。

一种方法是将input 事件附加到输入字段,以便每当输入字段值发生变化时,您都可以获取输入字段值,然后使用filter。根据输入字段的值过滤 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>

关于javascript - 对象数组中的html表单搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896979/

相关文章:

javascript - 在 promise 中定义异步函数

javascript - 动画图像 slider 在 Chrome 中闪烁

javascript - 在当前类(class)中添加一个具有相同 3 类(class)的类(class)

javascript - Bootstrap 导航栏汉堡菜单不起作用

php - 尝试读取数组上的属性 "title"(错误异常)Laravel Php

php - 合并数组,即使它们不存在于 PHP

php 中的 Javascript 函数不起作用

javascript - 如何更改 Bootstrap 选项卡淡出速度?

javascript - Phantomjs page.content 未检索页面内容

php - SPL 与数组 : When should we use SPL and when should we use Array in PHP?