使用Cookie 臨時存值

商品詳細:數組

//cookie零時存購物車
function addcar() {
  //判斷cookie是否有值
  if (getCookie("shopcar") == null) {
  //數組類型
  setCookie("shopcar", "[]");
  }

  //這裏舉例子,值寫死   
var obj = {     Name: "球鞋",     Price: "1200"   };   //獲取值,此時爲字符串類型   var liststr = getCookie('shopcar');   //類型轉換   var list = JSON.parse(liststr);   //追加值   list.push(obj);   //保存到cookie中   setCookie("shopcar", JSON.stringify(list));   location.href = "/Default/ShopCar"; }

 

 

購物車:cookie

//cookie加載購物車
function load() {
  //獲取值,此時爲字符串類型
  var liststr = getCookie("shopcar");
  //類型轉換
  var list = JSON.parse(liststr);
  $("#tb").empty();
  $(list).each(function () {
  $("#tb").append(
      '<tr>' +
      '<td>' + this.Name + '</td>' +
      '<td>' + this.Price + '</td>' +
      '</tr>'
    )
  })
}
load();

 

JavaScript:app

/**
* cookie中存值
* */
function setCookie(name, value) {
  if (value) {
    var days = 1; //定義一天
    var exp = new Date();
    exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
    // 寫入Cookie, toGMTString將時間轉換成字符串
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString;
  }
};
/** * cookie中取值 * */ function getCookie(name) {    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //匹配字段    if (arr = document.cookie.match(reg)) {      return unescape(arr[2]);    }
   else {      return null;    } };
相關文章
相關標籤/搜索