本地存儲(chǔ)localstorage(搜索框)
呈現(xiàn)的樣式
內(nèi)容
與下面銜接
可復(fù)制代碼
<!DOCTYPE html>
<html lang="en">
<head>
? <meta charset="UTF-8">
? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? <title>Document</title>
</head>
<style>
? * {
? ? padding: 0;
? ? margin: 0;
? }
? #ul {
? ? display: none;
? ? position: absolute;
? ? width: 170px;
? ? top: 26px;
? ? background-color: #ccc;
? }
</style>
<body>
? <input type="text" id="inp">
? <button id="btn">點(diǎn)擊搜索</button>
? <button id="del">刪除歷史記錄</button>
? <ul id="ul">
? </ul>
</body>
<script>
? var btn = document.getElementById('btn')
? var inp = document.getElementById('inp')
? var ul = document.getElementById("ul")
? var arr = []
? var val = null
? btn.onclick = function () {
? ? if (inp.value.trim().length !== 0) {
? ? ? val = inp.value
? ? ? inp.value = " "
? ? ? arr.push(val)
? ? ? var str = arr.join(',')
? ? ? localStorage.setItem('a', str)
? ? ? disappear()
? ? } else {
? ? ? alert('請輸入內(nèi)容')
? ? }
? }
? if (localStorage.getItem('a')) {
? ? str = localStorage.getItem('a')
? ? arr = str.split(",")
? ? Splicing()
? }
? inp.onclick = function () {
? ? ul.style.display = "block"
? ? Splicing()
? ? var tash = document.querySelectorAll("#ul>li")
? ? for (var i = 0; i < tash.length; i++) {
? ? ? tash[i].onclick = function () {
? ? ? ? inp.value = this.innerHTML
? ? ? ? disappear()
? ? ? }
? ? }
? }
? document.onmouseup = function () {
? ? disappear()
? }
? document.getElementById('del').onclick = function () {
? ? localStorage.removeItem("a")
? ? arr = []
? ? str = ""
? ? ul.innerHTML = ""
? }
? function Splicing() {
? ? var li = " "
? ? for (var i = 0; i < arr.length; i++) {
? ? ? li += "<li>" + arr[i] + "</li>"
? ? }
? ? ul.innerHTML = li
? }
? function disappear() {
? ? ul.style.display = "none"
? }
</script>
</html>