解决问题:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>修改代码,右边会自动显示结果</title>
<!--适应移动端-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--css样式-->
<style>
body {
background-color: #EBEBEB
}
.aaa {
background-color: #CB4F51;
padding: 10px;
display: block
}
</style>
<!--引用jquery库-->
<script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<input id="wt" type="text"></input>
<input type="button" class="sy_p2" value="搜索"></input>
<ul class="search-history-list"></ul>
<script type="text/javascript">
$(document).ready(function() {
function search() {
//.sy_p2 点击搜索按钮
$(".sy_p2").click(function(event) {
var key = $("#wt").val();
if (key) {
event.stopPropagation();
//调用底下的方法
searchHistory($("#wt").val());
//console.log(localStorage);
$("#sousuo").submit();
}
});
}
search();
function searchHistory(search_value) {
var len = 5; //设定存储的历史记录个数
if (search_value != "" && !judgeRepeat(search_value)) {
insertToHistoryList(search_value, len); /*将搜索结果插入到历史记录中*/
if (localStorage.length < len) //0 1 2 3 4
{
localStorage.setItem(localStorage.length, search_value);
} else {
for (var i = 0; i < len; ++i) {
if (i == len - 1) {
localStorage.setItem(i, search_value);
return;
}
var next_value = localStorage.getItem(i + 1);
localStorage.setItem(i, next_value);
}
}
}
}
/*如果搜索结果与本地存储相同,
则不行存储
*/
function judgeRepeat(search_value) {
var repeat_bool = false;
for (var key in localStorage) {
if (search_value == localStorage.getItem(key)) {
return true;
}
}
}
/*将搜索结果插入到历史记录中*/
function insertToHistoryList(search_value, len) {
if (search_value != null) {
var str = '<li><span>' + search_value + '<span></li>';
} else {
var str = '';
}
if ($(".search-history-list").children().length == 0) {
$(".search-history-list").append($(str));
} else {
if ($(".search-history-list").children().length < len) {
$(str).insertBefore($(".search-history-list li:eq(0)"));
} else {
$(".search-history-list li:last").remove(); //超过len个则移除最后一个
$(str).insertBefore($(".search-history-list li:eq(0)"));
}
}
}
/*初始化历史记录列表*/
function buildHistory() {
for (var i = 0; i < localStorage.length; ++i) {
var search_name = localStorage.getItem(localStorage.length - 1 - i);
if (search_name != null) {
var str = '<li><span οnclick="window.location.href=\'{url answer/search}?word=' + search_name + '\'">' + localStorage.getItem(localStorage.length - 1 - i) + '</span>' +
'</li>';
} else {
var str = '';
}
$(str).appendTo($(".search-history-list"));
}
}
buildHistory();
/*清空历史搜索记录*/
$(".clear-history").click(function(event) {
event.stopPropagation();
localStorage.clear();
$(".search-history-list").empty();
//console.log("History has been cleared");
});
});
</script>
</body>
</html>