jQuery Cookie 实现商品浏览历史记录功能

作者:青柠时间:2026-10-29 00:20:13浏览:190

本文介绍如何利用 jQuery 和 jquery.cookie.js 插件实现商品浏览历史记录功能。通过获取页面元素属性,将图片、名称、URL、价格和销量拼接存入 Cookie,并在页面加载时读取解析,动态生成推荐列表展示给用户,同时提供清空历史记录的方法。

引入依赖与写入历史记录

首先需引入 jquery.cookie.js 脚本



第一步,编写写入 Cookie 的 JavaScript 代码


具体实现代码如下:

 
// 开始写入浏览记录至 JSCookied
var img=$("#ProductImgurl").attr("jqimg");
var name=$("#ProductDetail_ctl00_LabelName").text();
var url=location.href;
var price=$("#ProductDetail_ctl00_LabelShopPrice").text();
var sellcount=$("#ProductDetail_ctl00_lblSaleNumber").text();
var hc=img+"|"+name+"|"+url+"|"+price+"|"+sellcount;
if($.cookie("history")!=null)
{ 
if($.cookie("history").indexOf(name)==-1)
{ 
$.cookie("history",hc+"*"+$.cookie("history"),{expires:8,domain:'.groupfly.com',path:"/"});
} 
} 
else
{ 
$.cookie("history",hc,{expires:8,domain:'.groupfly.com',path:"/"});
} 
// 结束写入浏览记录至 JSCookied

读取与展示历史记录

第二步,读取 Cookie 中的历史记录


相关代码示例如下:

 
<script type="text/javascript" charset="utf-8">
// 读取存储的历史记录
$(function(){
var hc=$.cookie("history");
if(hc!=null)
{ 
if(hc.indexOf("*")!=-1)
{ 
var splithtml=hc.split("*");
var xhtml=new Array();
var hlength=splithtml.length;
if(parseInt(hlength)>4)
hlength=4;
for(var i=0;i<parseInt(hlength);i++)
{ 
xhtml.push('<div class="tuijian"><div class="tjname"><a href="'+splithtml[i].split("|")[2]+'">'+splithtml[i].split("|")[1].substr(0, 17)+'</a></div>');
xhtml.push('<div class="tjimga"><a href="'+splithtml[i].split("|")[2]+'"><img src="'+splithtml[i].split("|")[0]+'_160x160.jpg" alt="'+splithtml[i].split("|")[1]+'" /></a><p>¥'+splithhtml[i].split("|")[3]+'</p></div>');
xhtml.push('<div class="otherInfo clearfix"><span>已销售<b>'+splithtml[i].split("|")[4]+'</b>笔</span><a href="'+splithtml[i].split("|")[2]+'">再看看</a></div></div>');
} 
xhtml.push('<div class="tr"><a href="javascript:clearcookied();">清空记录</a></div>');
$("#MyHistory").append(xhtml.join(""));
} 
else{
var xhtml=new Array();
xhtml.push('<div class="tuijian"><div class="tjname"><a href="'+hc.split("|")[2]+'">'+hc.split("|")[1].substr(0, 17)+'</a></div>');
xhtml.push('<div class="tjimga"><a href="'+hc.split("|")[2]+'"><img src="'+hc.split("|")[0]+'_160x160.jpg" alt="'+hc.split("|")[1]+'" /></a><p>¥'+hc.split("|")[3]+'</p></div>');
xhtml.push('<div class="otherInfo clearfix"><span>已销售<b>'+hc.split("|")[4]+'</b>笔</span><a href="'+hc.split("|")[2]+'">再看看</a></div></div>');
xhtml.push('<div class="tr"><a href="javascript:clearcookied();">清空记录</a></div>');
$("#MyHistory").append(xhtml.join(""));
} 
} 
else
{ 
$("#MyHistory").append("<li>暂无浏览记录</li>");
} 
}); 
function clearcookied()
{ 
$.cookie('history',null,{expires:1,domain:'.nrqiang.com'});
$("#MyHistory").html("<li>暂无浏览记录</li>");
} 
$(function() {
$("img").each(function(){$(this).attr("src",$(this).attr("original"));});
}); 
</script>
作者最新文章