关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

js实现搜索历史记录功能-马冬明-翼通云

发布时间:2019-09-29 11:51:53

html代码


<input name="keywords" id="keywords" type="text" class="sso_wk" x-webkit-speech="" autofocus placeholder="请输入您要搜索产品" οnkeydοwn="if(event.keyCode==13){SiteSearch();return false};">

<input name="" class="sso_an" type="button" οnclick="SiteSearch();">

 

<div class="lsss">历史搜索:</div>

<div class="sslb" id="lssslb">

</div>

————————————————

js代码

//产品搜索并存值

var thisurl="search.aspx?action=search";

function SiteSearch(){

    var sszd = $("#keywords").val();

    setHistoryItems(sszd);

    location.href=thisurl+"&sszd="+sszd+"";

};

//取值写入页面

$(function(){

    var str=localStorage.historyItems;

    var s = '';

    if(str==undefined){

        s='<div class="rmssts">暂无搜索记录...</div>';

        $("#lssslb").append(s);

    }else{

        var strs= new Array();

        strs=str.split("|");

        for(var i=0;i<strs.length;i++){

            s+= "<a href='search.aspx?action=search&sszd="+strs[i]+"' >"+strs[i]+"</a>";

        }

        $("#lssslb").append(s+'<input type="button" class="scls" οnclick="clearHistory();" value="清除历史记录">');

    }

});

//存值方法,新的值添加在首位

function setHistoryItems(keyword) {

    let { historyItems } = localStorage;

    if (historyItems === undefined) {

        localStorage.historyItems = keyword;

    } else {

        historyItems = keyword + '|' + historyItems.split('|').filter(e => e != keyword).join('|');

        localStorage.historyItems = historyItems;

    }

};

//清除值

function clearHistory() { 

    localStorage.removeItem('historyItems');

    var div = document.getElementById("lssslb");

    while(div.hasChildNodes()) //当div下还存在子节点时 循环继续

    {

        div.removeChild(div.firstChild);

    }

    $("#lssslb").append('<div class="rmssts">暂无搜索记录...</div>');

}

//存值方法,新的值添加在首位

function setHistoryItems(keyword) {

    let { historyItems } = localStorage;

    if (historyItems === undefined) {

        localStorage.historyItems = keyword;

    } else {

        historyItems = keyword + '|' + historyItems.split('|').filter(e => e != keyword).join('|');

        localStorage.historyItems = historyItems;

    }

};

//清除值

function clearHistory() { 

    localStorage.removeItem('historyItems');

    var div = document.getElementById("lssslb");

    while(div.hasChildNodes()) //当div下还存在子节点时 循环继续

    {

        div.removeChild(div.firstChild);

    }

    $("#lssslb").append('<div class="rmssts">暂无搜索记录...</div>');

}




/template/Home/Zkeys/PC/Static