本文實例講述了jQuery.cookie.js實現(xiàn)記錄最近瀏覽過的商品功能。分享給大家供大家參考,具體如下:
1、jquery.cookie.js
/*jquery.cookie.js */jquery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } var path = options.path ? '; path=' + options.path : ''; var domain = options.domain ? '; domain=' + options.domain : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }};2、實現(xiàn)最近瀏覽過的商品
var cookieName = "PrdIDCookie"; //cookie名稱var nid; //最新訪問的商品IDvar N = 5; //設(shè)置cookie保存的瀏覽記錄的條數(shù)//記錄最近瀏覽過的商品function HistoryRecord() { var historyp; nid = $("#PrdID").val(); if (nid == null || nid == "") { return; } //判斷是否存在cookie if ($.cookie(cookieName) == null) //cookie 不存在 { //創(chuàng)建新的cookie,保存瀏覽記錄 $.cookie(cookieName, nid, { expires: 7, path: '/' }); } else //cookies已經(jīng)存在 { //獲取瀏覽過的商品編號ID historyp = $.cookie(cookieName); }; //分解字符串為數(shù)組 var pArray = historyp.split(','); //最新訪問的商品編號放置載最前面 historyp = nid; //判斷是該商品編號是否存在于最近訪問的記錄里面 var count = 0; for (var i = 0; i < pArray.length; i++) { if (pArray[i] != nid) { historyp = historyp + "," + pArray[i]; count++; if (count == N - 1) { break; } } } //修改cookie的值 $.cookie(cookieName, historyp);}//獲取最近瀏覽過的商品function BindHistory() { var historyp = ""; if ($.cookie(cookieName) != null) //cookie 不存在 { //獲取瀏覽過的商品ID historyp = $.cookie(cookieName); } if (historyp == null && historyp == "") { return; } else { var prdIDs = []; //將商品ID以列表或數(shù)據(jù)的方式保存 var pArray = historyp.split(','); for (var i = 0; i < pArray.length; i++) { if (pArray[i] != "") { //alert(pArray[i]); prdIDs.push(pArray[i]); } } //--->請求商品詳細詳細... }}更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jQuery的cookie操作技巧總結(jié)》、《jQuery擴展技巧總結(jié)》、《jQuery常用插件及用法總結(jié)》、《jQuery表格(table)操作技巧匯總》、《jQuery常見經(jīng)典特效匯總》及《jquery選擇器用法總結(jié)》
希望本文所述對大家jQuery程序設(shè)計有所幫助。
新聞熱點
疑難解答