You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于jQuery代码实现最多5条localStorage搜索历史记录功能?

Solution for Saving Up to 5 Recent Search History Entries

Hey there! Let's tweak your code to keep track of up to 5 recent searches and display them properly. The core issue right now is that you're storing a single value in localStorage—we need to switch to storing an array instead, then manage that array to keep it trimmed to 5 entries. Here's a step-by-step fix:

Step 1: Update the Storage Logic

Instead of saving just the latest search, we'll:

  • Retrieve existing search history from localStorage (parse it from a string to an array)
  • Remove duplicate entries (so the same search doesn't show up multiple times)
  • Add the new search to the top of the list
  • Trim the array to keep only the most recent 5 entries
  • Save the updated array back to localStorage

Step 2: Create a Display Function

We'll make a reusable function to render the search history on the page, whether it's on page load or after a new search.

Full Working Code

// Handle search button click
$('#hledat').click(function() {
  // Get the new search value (trim to avoid empty spaces)
  const newSearch = $('#mesto').val().trim();
  
  // Don't process empty inputs
  if (!newSearch) return;

  // Get existing history from localStorage, or initialize empty array
  let searchHistory = JSON.parse(localStorage.getItem('searchHistory')) || [];

  // Remove duplicates: filter out any existing entry matching the new search
  searchHistory = searchHistory.filter(item => item !== newSearch);

  // Add the new search to the BEGINNING of the array (so latest shows first)
  searchHistory.unshift(newSearch);

  // Keep only the first 5 entries (most recent)
  if (searchHistory.length > 5) {
    searchHistory = searchHistory.slice(0, 5);
  }

  // Save the updated history back to localStorage
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory));

  // Update the displayed history
  displaySearchHistory();
});

// Function to render search history on the page
function displaySearchHistory() {
  const searchHistory = JSON.parse(localStorage.getItem('searchHistory')) || [];
  const $displayElement = $('#val');

  // Handle empty history case
  if (searchHistory.length === 0) {
    $displayElement.text('No search history yet');
    return;
  }

  // Render as a bulleted list (you can adjust this to fit your UI)
  const historyItems = searchHistory.map(search => `<li>${search}</li>`).join('');
  $displayElement.html(`<ul>${historyItems}</ul>`);

  // If you prefer plain text instead of a list, use this line instead:
  // $displayElement.text(searchHistory.join(' • '));
}

// Load and display history when the page first loads
$(document).ready(function() {
  displaySearchHistory();
});

Key Explanations

  • JSON.parse/JSON.stringify: LocalStorage only stores strings, so we convert our array to a string when saving, and parse it back to an array when retrieving.
  • Duplicate Removal: The filter method ensures we don't keep multiple copies of the same search.
  • unshift: Adds the new search to the start of the array, so the most recent entry is always first.
  • slice(0,5): Truncates the array to a maximum of 5 entries, discarding the oldest ones.
  • Page Load Initialization: The $(document).ready call ensures the history is displayed as soon as the page loads, not just after a search.

内容的提问来源于stack exchange,提问作者vejce4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:21:13