gpt4 book ai didi

javascript - 对对象数组和对象 Div 使用过滤器

转载 作者:行者123 更新时间:2023-11-28 03:07:06 25 4
gpt4 key购买 nike

这是我的代码:

HTML

  <input type="text" id=“search”>
<div id = “items”></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。

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

最佳答案

在你的过滤器函数中,你可以在那里生成所有的 html,但我更愿意将它们分开。在我看来,你有 3 个不同的部分:

  • 您的数据
  • 过滤函数,用于根据搜索词过滤数据
  • HTML 生成器函数,可根据您的数据生成 html

这是将所有内容整合在一起的快速方法

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>

或者,您可以隐藏 DOM 中的元素,而不是每次都重新生成新的 html 列表。

关于javascript - 对对象数组和对象 Div 使用过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60518192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com