我有一个待办事项列表,用户可以在其中添加注释。这些注释存储在本地存储中,提交输入后,值将显示在页面上。我想实现一个搜索栏,过滤列表,仅显示与用户输入的字符匹配的内容。
<div class="search-container mt-1">
<div class="search">
<input id="search-term" type="text" class="searchTerm" placeholder="Search..." oninput="search()">
<button type="submit" class="searchButton">
<i class="fa-solid fa-magnifying-glass"></i>
</button>
</div>
</div>
<div class="container">
<div class="flex justify-space">
<div class="text-space" id="scroll-container" onclick="scrollSection()">
<ul id="note"> </ul>
</div>
</div>
</div>
要实现一个搜索栏,根据用户输入过滤笔记列表并更新 DOM,您可以使用 JavaScript 执行以下步骤:
//
Retrieve notes from local storage (assuming you stored them as an array of strings)
let notes = JSON.parse(localStorage.getItem('notes')) || [];
function renderNotes() {
const noteList = document.getElementById('note');
noteList.innerHTML = ''; // Clear the previous list
notes.forEach((note) => {
const li = document.createElement('li');
li.textContent = note;
noteList.appendChild(li);
});
}
function search() {
const searchTerm = document.getElementById('search-term').value.toLowerCase();
const filteredNotes = notes.filter((note) =>
note.toLowerCase().includes(searchTerm)
);
// Update the DOM with the filtered notes
notes = filteredNotes;
renderNotes();
}
renderNotes()
显示所有注释,然后使用 search()
函数在用户键入时过滤注释。renderNotes();
search
函数附加到输入字段的 oninput
事件。<input id="search-term" type="text" class="searchTerm" placeholder="Search..." oninput="search()">
通过这些步骤,您的页面应该在用户在搜索输入字段中键入内容时更新注释列表,根据内容过滤注释并相应地更新 DOM。请务必根据您的笔记在本地存储中的存储方式来调整代码。