js实现搜索历史记录功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MMryyy/article/details/89477032

js实现搜索历史记录功能

首先我们来对比一下localStorage和sessionStorage:

localStorage生命周期是永久,这意味着除非用户显示在浏览器提供的UI上清除localStorage信息,否则这些信息将永远存在。

sessionStorage生命周期为当前窗口或标签页,一旦窗口或标签页被永久关闭了,那么所有通过sessionStorage存储的数据也就被清空了。
在这里插入图片描述

html

<div class="top">
			<div class="f1">
				<input type="text" class="input_top"/>
				<span>取消</span>
			</div>
		</div>
		<div class="history">
			<div class="history_top" style="display: none;">
				<span class="search">搜索历史</span>
				<span class="del">删除历史</span>
			</div>
			<div class="contain">
				<div class="fr"></div>
			</div>
		</div>
<style type="text/css">
	.top{
   
		background:whitesmoke;
		line-height: 70px;
    	padding-left: 10px;
	}
	.input_top{
   
		border-radius: 20px;
    	width: 
可以使用localStorage存储搜索历史记录,具体实现可以参考以下代码: 首先在HTML中添加一个搜索框和一个搜索历史记录列表: ```html <input type="text" id="searchBox"> <ul id="historyList"></ul> ``` 然后在JavaScript中实现搜索历史记录的存储和展示: ```js // 获取搜索历史记录 function getHistory() { let history = localStorage.getItem('searchHistory'); if (history) { return JSON.parse(history); } else { return []; } } // 添加搜索历史记录 function addHistory(keyword) { let history = getHistory(); if (history.indexOf(keyword) === -1) { history.push(keyword); localStorage.setItem('searchHistory', JSON.stringify(history)); } } // 清空搜索历史记录 function clearHistory() { localStorage.removeItem('searchHistory'); } // 展示搜索历史记录 function showHistory() { let history = getHistory(); let html = ''; for (let i = history.length - 1; i >= 0; i--) { html += '<li>' + history[i] + '</li>'; } document.querySelector('#historyList').innerHTML = html; } // 监听搜索框输入事件 document.querySelector('#searchBox').addEventListener('input', function() { let keyword = this.value.trim(); if (keyword) { addHistory(keyword); } }); // 页面加载时展示搜索历史记录 window.addEventListener('load', function() { showHistory(); }); // 清空搜索历史记录 document.querySelector('#clearBtn').addEventListener('click', function() { clearHistory(); showHistory(); }); ``` 以上代码实现搜索历史记录的存储、添加、清空和展示功能。当用户输入关键词时,将关键词添加到搜索历史记录中;页面加载时展示搜索历史记录;当用户点击清空按钮时,清空搜索历史记录并重新展示。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值