<div class="sy_div28">
<div class="sy_div23">
<span>搜索歷史</span>
<p class="clear-history">
<img src="{SITE_URL}static/pc/img/sy23.png"/>
<span>清空</span>
</p>
</div>
</div>
<ul class="search-history-list"></ul>
效果:

<script type="text/javascript">
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> '+
'<p class="sy_p37"><img src="{SITE_URL}static/pc/img/sy28.png"></p>'+
'</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 onclick="window.location.href=\'{url answer/search}?word='+search_name+'\'">'+localStorage.getItem(localStorage.length - 1 - i)+'</span>'+
'<p class="sy_p37"><img src="{SITE_URL}static/pc/img/sy28.png"></p>'+
'</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>
