本文就是要利用cookie插件,獲取用戶浏覽文章歷史記錄,並將用戶最近浏覽歷史記錄顯示在頁面。
在需要添加cookie的頁面加上如下js
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript">
$(function(){
var art_title = $("title").html();
var art_url = document.URL;
var history;
var json="[";
//json1是第一次注入cookie以後的第一個json,"此時還不是數組" 以點帶面的處理
var json1;
var canAdd= true;
//var json1=eval("({sitename:'dreamdu',sitedate:new Date(1980, 12, 17, 12, 0, 0)})");
if(!$.cookie("history")){
//第一次的時候需要初始化
history = $.cookie("history","{title:\""+art_title+"\""+",url:\""+art_url+"\"}");
}else {
//已經存在
history = $.cookie("history");
json1 = eval("("+history+")");
$(json1).each(function(){
if(this.title==art_title){
canAdd=false;
return false;
}
})
if(canAdd){
$(json1).each(function(){
json = json + "{\"title\":\""+this.title+"\",\"url\":\""+this.url+"\"},";
})
json = json + "{\"title\":\""+art_title+"\",\"url\":\""+art_url+"\"}]";
$.cookie("history",json,{expires:1});
}
}
})
</script>
在展示歷史記錄的頁面添加如下js
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript">
$(function(){
if($.cookie("history")){
var json = eval("("+$.cookie("history")+")");
var list ="";
$(json).each(function(){
list = list + "<li><a href='"+this.url+"' target='_blank'>"+this.title+"</a></li>";
alert(this.url);
})
$("#list").html(list);;
}
});
</script>
</head>
以上內容是小編給大家分享的通過Jquery.cookie.js實現展示浏覽網頁的歷史記錄,希望大家喜歡。