localStorage缓存:中文静网的历史浏览记录与收藏夹是怎么实现的

查看 41|回复 0
作者:零久网络   
大家发现没,中文静网的首页居然有浏览记录,作为一个全静态托管的网站,他是怎么实现的?其实也很简单,让我们来看下代码和效果吧
1、主页:https://cnj8.com/   的javascript代码是:
if(window.localStorage){
var cnj8_his=JSON.parse(localStorage.getItem('cnj8_his'));
if(cnj8_his==null || typeof cnj8_his !='object'){cnj8_his=[];
document.getElementById("medical-recommend-list").innerHTML='无记录';
}else{
var thtml='';
for (var i = 0; i '+cnj8_his['t']+'[/url]';
if(i>5) break;
}
document.getElementById("medical-recommend-list").innerHTML =thtml;
}
}
2、查看历史记录:https://cnj8.com/his.html     的javascript代码是:
if(window.localStorage){
var cnj8_his=JSON.parse(localStorage.getItem('cnj8_his'));
if(cnj8_his==null || typeof cnj8_his !='object'){cnj8_his=[];
document.getElementById("medical-recommend-list").innerHTML='无记录';
}else{
var thtml='';
for (var i = 0; i '+cnj8_his['t']+'[/url]';
}
document.getElementById("medical-recommend-list").innerHTML =thtml;
}
}
3、查看收藏:https://cnj8.com/fav.html     的javascript代码是:
if(window.localStorage){
var cnj8_fav=JSON.parse(localStorage.getItem('cnj8_fav'));
if(cnj8_fav==null || typeof cnj8_fav !='object'){cnj8_fav=[];
document.getElementById("medical-recommend-list").innerHTML='无记录';
}else{
var thtml='';
for (var i = 0; i '+cnj8_fav['t']+'[/url]';
}
document.getElementById("medical-recommend-list").innerHTML =thtml;
}
}
4、文章浏览:https://cnj8.com/i/28/54999.html      的javascript代码是:
var nurl=window.location.href.split('?')[0];
var ntitle=document.title.split(' - ')[0];
if(window.localStorage){
var cnj8_his=JSON.parse(localStorage.getItem('cnj8_his'));
if(cnj8_his==null || typeof cnj8_his !='object')  cnj8_his=[];
cnj8_his.unshift({'u':nurl,'t':ntitle});
for (var i = 1; i 100) cnj8_his.pop();
localStorage.setItem('cnj8_his',JSON.stringify(cnj8_his));
/*收藏*/
}
var fav_bool=false;
function is_fav(){
if(window.localStorage){
var cnj8_fav=JSON.parse(localStorage.getItem('cnj8_fav'));
if(cnj8_fav==null || typeof cnj8_fav !='object'){document.getElementById("fav").innerText='加入收藏'; return false}
for (var i = 0; i 100) cnj8_fav.pop();
localStorage.setItem('cnj8_fav',JSON.stringify(cnj8_fav));
}
}
is_fav();
总结:4步,简简单单就实现了本地的浏览记录缓存和收藏夹功能,大家感觉去试试吧

代码, 收藏夹

您需要登录后才可以回帖 登录 | 立即注册