js实现搜索记录列表

<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>

效果:

js实现搜索记录列表

<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>
上一篇:JVM原理分析


下一篇:WebIM 聊天 Demo