前端实现模糊搜索功能代码实现
时间: 2023-04-05 21:05:10 浏览: 163
以下是一个简单的前端实现模糊搜索功能的代码实现:
HTML:
```
<input type="text" id="searchInput" placeholder="Search...">
<ul id="results"></ul>
```
JavaScript:
```
const searchInput = document.getElementById('searchInput');
const resultsList = document.getElementById('results');
searchInput.addEventListener('input', function() {
const searchTerm = searchInput.value.toLowerCase();
resultsList.innerHTML = '';
if (searchTerm.length < 3) {
return;
}
const filteredResults = data.filter(function(item) {
return item.name.toLowerCase().includes(searchTerm);
});
filteredResults.forEach(function(item) {
const li = document.createElement('li');
li.textContent = item.name;
resultsList.appendChild(li);
});
});
const data = [
{ name: 'Apple' },
{ name: 'Banana' },
{ name: 'Cherry' },
{ name: 'Durian' },
{ name: 'Elderberry' },
{ name: 'Fig' },
{ name: 'Grape' },
{ name: 'Honeydew' },
{ name: 'Iced Tea' },
{ name: 'Jicama' },
{ name: 'Kiwi' },
{ name: 'Lemon' },
{ name: 'Mango' },
{ name: 'Nectarine' },
{ name: 'Orange' },
{ name: 'Pineapple' },
{ name: 'Quince' },
{ name: 'Raspberry' },
{ name: 'Strawberry' },
{ name: 'Tangerine' },
{ name: 'Ugli Fruit' },
{ name: 'Vanilla Bean' },
{ name: 'Watermelon' },
{ name: 'Xigua' },
{ name: 'Yellow Squash' },
{ name: 'Zucchini' }
];
```
这段代码监听输入框的输入事件,当输入框中的文本发生变化时,会根据输入的文本进行模糊搜索。如果输入的文本长度小于3,则不进行搜索。搜索结果会显示在一个无序列表中。
阅读全文