页面重新加载后保持购物车的价值

时间:2021-03-20 16:40:14

标签: javascript html css ajax

我正在为课程项目复制一个杂货店网页,并想知道如何在刷新网页后仍保留购物车中的值。如果我没有提供足够的信息,请告诉我...

       <button type="button" id="subtract" onclick="decrease()">-</button>
       <input class="quantity-box" type="text" id="text" value="0">
       <button type="button" id="add" onclick="increase()">+</button>
       <br>
      <button class="add-button" onclick="add(1)"><i class="fa fa-cart-plus"></i>&nbsp ADD TO CART</button>



<div class="cart">
      <h3 class="aisle-header">Shopping Cart</h3>
      <!-- list of the articles in the cart -->
      <ul id="items">
      </ul>
      <h3 id="total" style="text-align: right;">Total: 0 $</h3>
  </div> 
/* This script is to add increment and decrement quanity */
function decrease(){
var textBox = document.getElementById("text");
if (textBox.value > 0){
  textBox.value--;
  localStorage.setItem('quantity', textBox.value);
}
}

function increase(){
 var a = 1;
 var textBox = document.getElementById("text");
 textBox.value++;
 localStorage.setItem('quantity', textBox.value);
}

window.onload = function() {
var textBox = document.getElementById("text");
textBox.value = localStorage.getItem('quantity');
}


/* This script is to add quantity to cart */

      // Cost of all products in the cart
      var total = 0;
      // Index
      var i = 1;
      // List of the amount of every product in the cart
      var itemCost = [];
      // Add to cart
      function add(n){
          // Getting all Id of the selected shirt(brand ex: nike, price and quantity)
          brand = "name";
          priceId = "price";
          quantityId = "text";
          // Getting details of the selected shirt
          // brand
          name = document.getElementById(brand).innerHTML;
          // price
          price = document.getElementById(priceId).innerHTML;
          // quantity
          quantity = document.getElementById(quantityId).value;
          // Creating a li element to add it to ul
          var node = document.createElement("LI");
          // id of li element
          item = "item"+i;
          node.setAttribute("id", item)
          // cost of the selected shirt
          itemCost[i-1] = Number(price) * Number(quantity);
          // Updating the index i
          i += 1;
          // text of the li element
          var textnode = document.createTextNode(name+" "+quantity+" x $"+price+" ");
          // add the text to li element
          node.appendChild(textnode);
          // add li element to ul list
          document.getElementById("items").appendChild(node);

          total += Number(price) * Number(quantity);
          // update the total
          document.getElementById("total").innerHTML = "Total: " + total.toFixed(2) + " $";

          // Add a remove button
          document.getElementById(item).innerHTML += '<button class= "deleItem" onclick="deleItem('+"'"+item+"'"+')">X</button>';
          // you have to respect the order of: '' and ""

      }

      // Remove a product from the cart
      function deleItem(eId){
          document.getElementById(eId).remove();
          // slice is string method
          // eId (element Id) contain root + number (ex: item4)
          // n is the number in eId
          n = Number(eId.slice(-1)) - 1;
          // remove the cost of the product deleted from the cart
          total -= itemCost[n];
          // Updating the cost of products in the cart
          document.getElementById("total").innerHTML = "Total: " + total.toFixed(2) + " $";
      }

注意:我可以使用 AJAX,但我对此并不熟悉,因此如果解决方案中包含它,那么简要说明就足够了。 HTML/JAVASCRIPT/CSS/AJAX

1 个答案:

答案 0 :(得分:1)

Cookies 是为你需要做的事情而设计的,你可以像这个例子一样简单地使用它们和一个元素数组:

var cart = ['Apple', 'Pear', 'Banana'];
var json_str = JSON.stringify(cart);
setCookie('myCart', json_str, '30'); //This cookie lasts for 30 days

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

然后你可以像这样读取之前创建的cookie:

var json_str = getCookie('myCart');
var cart = JSON.parse(json_str);

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

要查看 cookie,只需打开 Chrome DevTools(F12 键或检查),转到“应用程序”选项卡,在左侧您会找到一个带有 Cookie 项的菜单。

请记住,Chrome 不允许本地文件使用 cookie,因此对于save data locally,您应该这样做:

// Save data value
localStorage.setItem("name", "John");

// Retrieve data value
var name = localStorage.getItem("name");
相关问题