<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>搜索框</title>
<script>
window.onload = function () {
var list = document.querySelector('.ul');
var searchInput = document.querySelector('.input');
var searchBtn = document.querySelector('.button');
var myHistory = [];
/**
* 需求1// 如果搜索框不为空,我们则将搜索词添加到开头
* 2// 清空显示的搜索关键词列表,防止显示
* 3.通过循环遍历,显示所有的搜索关键词
* 4如果数组的长度大于 5,那么便移除旧的搜索关键词
* 5 清空并聚焦到搜索框,准备下一次的搜索
*/
/**
* 案例心得
* 如果通过一个判断 实现的话 就是要 后面书写的东西 都写在if 语句的后面
*/
searchBtn.addEventListener("click", () => {
if (searchInput.value !== "") {
myHistory.unshift(searchInput.value);
for (let i = 0; i < myHistory.length; i++) {
//获取数组的每一项
let arr_item = myHistory[i];
//创建li标签
let list_item = document.createElement("li");
//li标签的内容就是 数组中的数据
list_item.textContent = arr_item;
//将li标签插入到页面当中
list.appendChild(list_item);
};
if (myHistory.length >= 5) {
//清除旧的搜索词
myHistory.pop();
};
searchInput.focus();
}
})
}
</script>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
;
}
.test_ul {
border: 2px solid skyblue;
}
</style>
</head>
<body>
<form action="">
<input type="text" class="input" placeholder="请输入有效的信息" />
<button class="button">Search</button>
<ul class="ul">
</ul>
</body>
</html>