如何在搜索时将用户输入与本地存储进行比较并更新 DOM?

问题描述 投票:0回答:1

我有一个待办事项列表,用户可以在其中添加注释。这些注释存储在本地存储中,提交输入后,值将显示在页面上。我想实现一个搜索栏,过滤列表,仅显示与用户输入的字符匹配的内容。

<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>
javascript html css search local-storage
1个回答
0
投票

要实现一个搜索栏,根据用户输入过滤笔记列表并更新 DOM,您可以使用 JavaScript 执行以下步骤:

  1. 从本地存储检索数据并初始化您的笔记列表。
// 

    Retrieve notes from local storage (assuming you stored them as an array of strings)
    let notes = JSON.parse(localStorage.getItem('notes')) || [];

  1. 创建一个函数来在页面上呈现注释。
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);
  });
}
  1. 为搜索功能创建一个函数。
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();
}
  1. 确保您最初调用
    renderNotes()
    显示所有注释,然后使用
    search()
    函数在用户键入时过滤注释。
renderNotes();
  1. search
    函数附加到输入字段的
    oninput
    事件。
<input id="search-term" type="text" class="searchTerm" placeholder="Search..." oninput="search()">

通过这些步骤,您的页面应该在用户在搜索输入字段中键入内容时更新注释列表,根据内容过滤注释并相应地更新 DOM。请务必根据您的笔记在本地存储中的存储方式来调整代码。

© www.soinside.com 2019 - 2024. All rights reserved.