本地存储 最近搜索记录

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<title></title>
		<style>
			*{
				margin: 0;
				padding: 0;
			}
			header{
				line-height: 40px;
				border-bottom: 1px solid #ccc;
			}
			.searchList span {
				padding: 6px;
			}
		</style>
	</head>
	<body>
		<header>
			<input type="text" id="searchText">
			<span id="toSearch">搜索</span>
		</header>
		<section class="searchList" id="searchList">
			<h3>最近搜索</h3>
			<!-- <span>鞋子</span> -->
		</section>
		<script>
			var searchText=document.getElementById('searchText'),
			toSearch=document.getElementById('toSearch'),
			searchList=document.getElementById('searchList');
			//存储的值
			console.log(localStorage.getItem('search'));
			// var arrSearch= [];
			var arrSearch = JSON.parse(localStorage.getItem('search')) || [];
			// console.log(localStorage.getItem('search'))
			
			//点击搜索按钮
			toSearch.onclick=function(){
				var sSpan=document.createElement('span');
				//文本框输入,点击搜索的值
				sSpan.innerText=searchText.value;
				console.log(searchText.value);
				searchList.insertBefore(sSpan,searchList.getElementsByTagName('span')[0]);
				
				//最近搜索记录:首先存放的得是个数组,不然会挤掉前一个
				// 而且本地存储存进去的永远是字符串,所以存放要变成字符串,取出的时候再变回来
				arrSearch.unshift(searchText.value);
				localStorage.setItem('search',JSON.stringify(arrSearch));
				
				searchText.value = '';
			}
			
			//本地存储
			var storage=JSON.parse(localStorage.getItem('search'));
			storage.forEach(function(item,index){
				console.log(item);
				var sSpan = document.createElement('span');
					sSpan.innerText = item;
					searchList.appendChild(sSpan);
			})
		</script>
	</body>
</html>

 

posted @   zongkm  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示