首页 > 解决方案 > 对对象数组和 Div 使用过滤器

问题描述

这是我的代码:

HTML

  <input type="text" id=“search”&gt;
  <div id = “items”&gt;</div>

JAVASCRIPT

var items = 
    [ { name: 'toy1', price: '12.00', quantity: 12 } 
    , { name: 'toy2', price:  '1.00', quantity:  5 } 
    , { name: 'toy3', price: '11.00', quantity:  2 } 
    , { name: 'toy4', price:  '1.00', quantity:  2 } 
    ] 

items.filter(name(function)){

});

这是一个前任。我想做的事情:https
://www.w3schools.com/howto/howto_js_filter_lists.asp 对于我的情况,我希望用户能够按名称搜索,但我被困在函数内要写什么。
我想要 div 中的每个对象,所以当用户按名称搜索时,
ex:toy4,然后其他 div 过滤掉,只显示包含 toy4 信息的 div。
我知道过滤器是在这里使用的正确方法,但我不确定如何链接用户从输入框中输入的内容并“检查/过滤” div 以仅显示用户正在搜索的内容并将每个对象放入 div .

*我只能使用javascript。

注意 我已经阅读了大多数与我类似的问题,但它们使用的语言是我尚未学习或无法回答我的问题。

标签: javascripthtmlarraysjavascript-objects

解决方案


In your filter function, you could just generate all your html there, but I would prefer to keep them seperate. It looks to me like you have 3 different pieces:

  • Your data
  • A filter function to filter the data based off the search term
  • An HTML generator function that will generate your html based off your data

Here's a quick way of bringing it all together

const items = [{
    name: 'toy1',
    price: '12.00',
    quantity: 12
  },

  {
    name: 'toy2',
    price: '1.00',
    quantity: 5
  },
  {
    name: 'toy3',
    price: '11.00',
    quantity: 2
  },
  {
    name: 'toy4',
    price: '1.00',
    quantity: 2
  }
];

/**
* Create a function to generate your elements based
* off the passed in array of data
*/
function makeList(data) {
  // Grab your container
  const container = document.getElementById('items');
  // Clear it (reset it)
  container.innerHTML = '';
  // Iterate through your data and create the elements
  // and append them to the container
  data.forEach(i => {
    const element = document.createElement('div');
    element.innerText = i.name;
    container.append(element);
  });
}

/**
* Create an event listener to react to
* search updates so you can filter the list.
* keyUp is used so that you wait for the
* user to actually finish typing that specific
* char before running. Otherwise, you'll be missing
* a char. (Try changing it to 'keypress' and see what happens)
*/
document.getElementById('search').addEventListener('keyup', function(e) {
  // Get the textbox value
  const searchTerm = e.target.value;
  // If no value, reset the list to all items
  if (!searchTerm) {
    makeList(items);
    return;
  }
  // Filter your list of data
  // based off the searchTerm
  const data = items.filter(i => i.name.toLowerCase().includes(searchTerm.toLowerCase()));
  // Pass the list filtered list of data to your makeList function
  // to generate your html
  makeList(data);
});

// Generate your initial list
makeList(items);
<input type="text" id="search">
<div id="items"></div>

Alternatively, you could just hide the elements in the DOM instead of regenerating a fresh html list each time.


推荐阅读