Home  >  Article  >  Web Front-end  >  JQ Cookie obtains browsing history

JQ Cookie obtains browsing history

巴扎黑
巴扎黑Original
2016-11-25 14:02:221657browse

I searched for the usage of js cookies and found that many of them are wrong. They are either very wrong or the usage is very old and the code is not written concisely. Finally, after doing it myself, I concluded that this demand is quite common and recorded it

var historyCount = 15; //保存历史记录个数
/**
 * 增加浏览历史记录
 * @return
 */
function setHistory(keyWord) {
        var keyWords = $.cookie('keyWord');
        if (keyWords) {
            if(keyWord) {
                var keys = keyWords.split(",");
                for (var i = keys.length - 1; i >= 0; i--) {
                    if (keys[i] == keyWord) {
                        keys.splice(i, 1);
                    }
                }
                keys.push(keyWord);
                if (keys.length >= historyCount) {
                    //删除最开始的多余记录
                    var count = keys.length - historyCount + 1; //需要删除的个数
                    keys.splice(0, count); //开始位置,删除个数
                }
                $.cookie('keyWord', keys.join(','), {expires: 365, path: '/'});
            }
        } else {
            $.cookie('keyWord', keyWord, {expires: 365, path: '/'});
        }
}
function  delHistory(){
    $.cookie("keyWord",null,{path:"/",expires: -1});
}
function  getHistory(){
    var keyWords = $.cookie('keyWord');
    if(keyWords) {
        var keys=  keyWords.split(",");
        var length = keys.length;
        if (length > 0) {
            $("#historyRecord").empty();
            var htmlString = "<dt>历史搜索</dt><dd>";
            for (var i = length - 1; i >= 0; i--) {
                htmlString += "<a href=&#39;javascript:;&#39; >" + keys[i] + "</a>";
            }
            htmlString += "</dd>";
            $("#historyRecord").html(htmlString)
        }
    }
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn