購物車案例

来源:https://www.cnblogs.com/ruo-shui-yi-fang/archive/2019/09/21/11564124.html
-Advertisement-
Play Games

學習前端以來,一直很好奇像京東,淘寶這種大型網站的購物車是怎麼做到統一的,就去搜索了一些資料吧!大致的看了一下,自己實戰了下,俗話說的好,讀萬卷書不如行萬里路!購物車只是一個很小的案例,但也可以去動手做一做,感受下過程!積少成多! 這案例主要是通過本地儲存來實現的,我用了兩種方法,一種是cookie ...


學習前端以來,一直很好奇像京東,淘寶這種大型網站的購物車是怎麼做到統一的,就去搜索了一些資料吧!大致的看了一下,自己實戰了下,俗話說的好,讀萬卷書不如行萬里路!購物車只是一個很小的案例,但也可以去動手做一做,感受下過程!積少成多!

這案例主要是通過本地儲存來實現的,我用了兩種方法,一種是cookie,另一種是localStorage。cookie會跟隨http發送給伺服器,並且有時間限制,在沒有設置時間時,預設過期時間是關閉瀏覽器就過期;localStorage是本地的,永久的,儲存的數據也更大!這是cookie和localStorage的區別!

!!!敲重點,我所寫的都是基於原生,沒有使用jQuery!

就先用cookie來實現下效果吧!

  1. 目前沒有後端,那就先自己模擬下後端傳輸數據;準備一個json文件,裡面存放的就是數據!類似下圖這樣!
  2. 引入之前封裝好的ajax和cookie的js文件,也可引入jQuery,但jQuery沒有提供cookie的方法,只有插件,網上下一個即可!
      下麵是封裝ajax的代碼
     1 function ajax(options){
     2     var {type,url,success,data,error,timeout}=options;
     3     data=data||{};
     4     type=type||"get";
     5     timeout=timeout||2000;
     6     var str="";
     7     for(var i in data){
     8         str+=`${i}=${data[i]}&`;
     9     }
    10     if(type=="get"){
    11         var d=new Date();
    12         url=url+"?"+str+"_yjyt="+d.getTime();
    13     }
    14     var xhr=new XMLHttpRequest();
    15     xhr.open(type,url);
    16     // console.log(url);
    17     xhr.onreadystatechange=function(){
    18         if(xhr.readyState==4&&xhr.status==200){
    19             success&&success(xhr.responseText);
    20             error=null;
    21         }else if(xhr.readyState==4&&xhr.status!=200){
    22             error&&error(xhr.status);
    23             success=null;
    24             error=null;
    25         }
    26     }
    27     setTimeout(()=>{
    28         error&&error(timeout);;
    29         success=null;
    30     },timeout);
    31     if(type=="post"){
    32         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    33         xhr.send(str);
    34     }else{
    35         xhr.send();
    36     }
    37 }

     接下來的是cookie的代碼

     1 function setCookie(key, val, options) {
     2     // console.log(options.expires);
     3     options = options || {};
     4     var path = "";
     5     if (options.path) {
     6         path = ";path=" + options.path;
     7     }
     8     var expires = "";
     9     if (options.expires) {
    10         var d = new Date();
    11         d.setDate(d.getDate() + options.expires);
    12         expires = ";expires=" + d;
    13         console.log(expires);
    14     }
    15     document.cookie = key + "=" + val + path + expires;
    16 }
    17 function getCookie(key) {
    18     // var arr=document.cookie;
    19     // console.log(arr);
    20     var arr = document.cookie.split(";");
    21     console.log(arr);
    22     for (var i = 0; i < arr.length; i++) {
    23         if (arr[i].split("=")[0] === key) {
    24             return arr[i].split("=")[1];
    25         }
    26     }
    27     return "";
    28 }
    29 function removeCookie(key, options) {
    30     options = options || {};
    31     options.expires = -1;
    32     // console.log(options);
    33     // console.log(key);
    34     setCookie(key, 23, options);
    35 }
  3. 接下來就是佈局,簡單點來,感受下就好,不好看可以自己後期通過css改,這都是寫小問題哈,我只說關鍵的地方!佈局簡陋,可以自行發揮哦!
    顯示商品列表的佈局
    1     <h2>這是商品列表<a href="car-local.html">去結算</a></h2>
    2     <div class="cont">
    3         <p>不好意思,賣完了!</p>
    4     </div>

     購物車的佈局

     1     <h2>這是結算頁<a href="shop.html">繼續購物</a></h2>
     2     <table border="1" rules="all" width="900" align="center">
     3         <thead>
     4             <tr>
     5                 <th>圖片</th>
     6                 <th>名字</th>
     7                 <th>價格</th>
     8                 <th>數量</th>
     9                 <th>操作</th>
    10             </tr>
    11         </thead>
    12         <tbody></tbody>
    13     </table>
  4. 下麵就到我們最關鍵得到部分了,我們先要獲取到用戶點擊了那個商品的假如購物車,然後要獲取數量,再保存進cookie里,然後拿到cookie中的數據渲染購物車的頁面,這麼一說感覺很簡單是吧,來,上代碼感受下!
    先獲取數據保存到cookie
     1 <script src="js/ajax.js"></script>
     2 <script src="js/cookie.js"></script>
     3 <script>
     4     class Shop {
     5         constructor() {
     6             this.url = "http://localhost/test/shopping/data/goods.json";
     7             this.cont = document.querySelector(".cont");
     8             this.init();
     9             this.addEvent();
    10         }
    11         init() {
    12             ajax({
    13                 url: this.url,
    14                 success: res => {
    15                     this.res = JSON.parse(res);
    16                     this.display()
    17                 }
    18             })
    19         }
    20         display() {
    21             var str = "";
    22             for (var i = 0; i < this.res.length; i++) {
    23                 str += `<div class="box" index="${this.res[i].goodsId}">
    24                             <img src="${this.res[i].img}" alt="">
    25                             <p>${this.res[i].name}</p>
    26                             <span>${this.res[i].price}</span>
    27                             <input type="button" value="加入購物車">
    28                         </div>`;
    29             }
    30             this.cont.innerHTML = str;
    31         }
    32         addEvent() {
    33             var that = this;
    34             this.cont.addEventListener("click", function (eve) {
    35                 var e = eve || window.event;
    36                 var target = e.target || e.srcElement;
    37                 if (target.type === "button") {
    38                     that.id = target.parentNode.getAttribute("index");
    39                     that.setcookie();
    40                 }
    41             });
    42         }
    43         setcookie() {
    44             this.goods = getCookie("goods") ? JSON.parse(getCookie("goods")) : [];
    45             if (this.goods.length < 1) {
    46                 this.goods.push({
    47                     id: this.id,
    48                     num: 1
    49                 });
    50             } else {
    51                 var onoff = 1;
    52                 for (var i = 0; i < this.goods.length; i++) {
    53                     if (this.goods[i].id == this.id) {
    54                         this.goods[i].num++;
    55                         onoff = 0;
    56                     }
    57                 }
    58                 if (onoff == 1) {
    59                     this.goods.push({
    60                         id: this.id,
    61                         num: 1
    62                     })
    63                 }
    64             }
    65             setCookie("goods", JSON.stringify(this.goods));
    66         }
    67     }
    68     new Shop;
    69 </script>
    拿到cookie的數據渲染購物車
     1 <script src="js/ajax.js"></script>
     2 <script src="js/cookie.js"></script>
     3 <script>
     4     class Car {
     5         constructor() {
     6             // 數據
     7             this.url = "http://localhost/test/shopping/data/goods.json";
     8             this.tbody = document.querySelector("tbody");
     9             this.init();
    10             // 綁定事件
    11             this.addEvent();
    12         }
    13         addEvent() {
    14             var that = this;
    15             // 事件委托
    16             this.tbody.addEventListener("click", function (eve) {
    17                 var e = eve || window.event;
    18                 var target = e.target || e.srcElement;
    19                 if (target.tagName === "SPAN") {
    20                     that.id = target.parentNode.parentNode.getAttribute("index");
    21                     target.parentNode.parentNode.remove();
    22                     that.removecookie();
    23                 }
    24             });
    25             this.tbody.addEventListener("input", function (eve) {
    26                 var e = eve || window.event;
    27                 var target = e.target || e.srcElement;
    28                 if (target.type === "number") {
    29                     // console.log(target.value);
    30                     that.id = target.parentNode.parentNode.getAttribute("index");
    31                     that.val = target.value;
    32                     that.updatecookie();
    33                 }
    34             })
    35         }
    36         updatecookie() {
    37             var i = 0;
    38             var onoff = this.goods.some((val, index) => {
    39                 i = index;
    40                 return val.id == this.id;
    41             });
    42             if (onoff) {
    43                 this.goods[i].num = this.val;
    44             }
    45             setCookie("goods", JSON.stringify(this.goods));
    46         }
    47         removecookie() {
    48             var i = 0;
    49             var onoff = this.goods.some((val, index) => {
    50                 i = index;
    51                 return val.id == this.id;
    52             });
    53             if (onoff) {
    54                 this.goods.splice(i, 1);
    55             }
    56             setCookie("goods", JSON.stringify(this.goods));
    57         }
    58         init() {
    59             var that = this;
    60             ajax({
    61                 url: this.url,
    62                 success: function (res) {
    63                     that.res = JSON.parse(res);
    64                     // console.log(that.res);
    65                     that.getcookie();
    66                 }
    67             })
    68         }
    69         getcookie() {
    70             this.goods = getCookie("goods") ? JSON.parse(getCookie("goods")) : [];
    71             // console.log(this.goods);
    72             this.display();
    73         }
    74         // 渲染頁面
    75         display() {
    76             var str = "";
    77             for (var i = 0; i < this.res.length; i++) {
    78                 for (var j = 0; j < this.goods.length; j++) {
    79                     if (this.res[i].goodsId == this.goods[j].id) {
    80                         str += `<tr index="${this.goods[j].id}">
    81                                     <td><img src="${this.res[i].img}"></td>
    82                                     <td>${this.res[i].name}</td>
    83                                     <td>${this.res[i].price}</td>
    84                                     <td><input type="number" value="${this.goods[j].num}" min=1 /></td>
    85                                     <td><span>刪除</span></td>
    86                                 </tr>`;
    87                     }
    88                 }
    89             }
    90             this.tbody.innerHTML = str;
    91         }
    92     }
    93 
    94     new Car;
    95 </script>

 以上就是cookie方法實現購物車的代碼!下麵我來說下用localStorage方法實現吧,其實佈局什麼都是一樣的,只是把cookie改成localStorage就可以了。我就只放js的代碼了哦

商品列表的js

 1     class shop {
 2         constructor() {
 3             this.cont = document.querySelector(".cont");
 4             this.url = "http://localhost/test/shopping/data/goods.json";
 5             this.init();
 6             this.addEvent();
 7         }
 8         init() {
 9             ajax({
10                 url: this.url,
11                 success: (res) => {
12                     this.res = JSON.parse(res);
13                     this.display();
14                 }
15             })
16         }
17         display() {
18             var str = "";
19             for (var i = 0; i < this.res.length; i++) {
20                 str += `<div class="box" index="${this.res[i].goodsId}">
21                             <img src="${this.res[i].img}" alt="">
22                             <p>${this.res[i].name}</p>
23                             <span>${this.res[i].price}</span>
24                             <input type="button" value="加入購物車">
25                         </div>`;
26             }
27             this.cont.innerHTML = str;
28         }
29         addEvent() {
30             var that = this;
31             this.cont.addEventListener("click", function (eve) {
32                 var e = eve || window.event;
33                 var target = e.target || e.srcElement;
34                 if (target.type === "button") {
35                     that.id = target.parentNode.getAttribute("index");
36                     that.setStorage();
37                 }
38             })
39         }
40         setStorage() {
41             this.goods = JSON.parse(localStorage.getItem("goods")) || [];
42             // console.log(this.goods.length);
43             // console.log(this.goods);
44             if (this.goods.length < 1) {
45                 this.goods.push({
46                     id: this.id,
47                     num: 1
48                 });
49             } else {
50                 var onoff = 1;
51                 for (var i = 0; i < this.goods.length; i++) {
52                     if (this.id == this.goods[i].id) {
53                         // console.log(this.arr[i])
54                        this.goods[i].num++;
55                        onoff=0;
56                     }
57                     if (onoff) {
58                         this.goods.push({
59                             id: this.id,
60                             num: 1
61                         });
62                     }
63                 }
64             }
65             localStorage.setItem("goods", JSON.stringify(this.goods));
66             // console.log(this.goods.length);
67             // this.goods=localStorage.getItem("id");
68             // console.log(this.goods);
69         }
70     }
71     new shop;

購物車的

 1     class Car {
 2         constructor() {
 3             this.tbody = document.querySelector("tbody");
 4             this.url = "http://localhost/test/shopping/data/goods.json";
 5             this.goods = JSON.parse(localStorage.getItem("goods"));
 6             // console.log(this.goods);
 7             this.init();
 8             this.addEvent();
 9         }
10         addEvent() {
11             var that = this;
12             this.tbody.addEventListener("click", function (eve) {
13                 var e = eve || window.event;
14                 var target = e.target || e.srcElement;
15                 if (target.tagName === "SPAN") {
16                     that.id = target.parentNode.parentNode.getAttribute("index");
17                     // console.log(that.id);
18                     target.parentNode.parentNode.remove();
19                     that.removeLocal();
20                 }
21             });
22             this.tbody.addEventListener("input",function(eve){
23                 var e=eve||window.event;
24                 var target=e.target||e.srcElement;
25                 if(target.type==="number"){
26                     that.id = target.parentNode.parentNode.getAttribute("index");
27                     // console.log(that.id);
28                     that.val=target.value;
29                     that.updateLocal();
30                 }
31             })
32         }
33         updateLocal(){
34             var i=0;
35             var onoff=this.goods.some((val,index)=>{
36                 i=index;
37                 return val.id=this.id;
38             });
39             if(onoff){
40                 this.goods[i].num=this.val;
41             }
42             localStorage.setItem("goods",JSON.stringify(this.goods));
43         }
44         removeLocal() {
45             var i=0;
46             var onoff=this.goods.some((val,index)=>{
47                 i=index;
48                 return val.id=this.id;
49             });
50             if(onoff){
51                 this.goods.splice(i,1);
52             }
53             localStorage.setItem("goods",JSON.stringify(this.goods));
54         }
55         init() {
56             ajax({
57                 url: this.url,
58                 success: (res) => {
59                     this.res = JSON.parse(res);
60                     // console.log(this.res);
61                     this.display();
62                 }
63             });
64         }
65         display() {
66             var str = "";
67             for (var i = 0; i < this.res.length; i++) {
68                 for (var j = 0; j < this.goods.length; j++) {
69                     if (this.res[i].goodsId === this.goods[j].id) {
70                         // console.log(1);
71                         str += `<tr index="${this.goods[j].id}">
72                                     <td><img src="${this.res[i].img}"></td>
73                                     <td>${this.res[i].name}</td>
74                                     <td>${this.res[i].price}</td>
75                                     <td><input type="number" value="${this.goods[j].num}" min=1 /></td>
76                                     <td><span>刪除</span></td>
77                                 </tr>`;
78 
79                     }
80                 }
81             }
82             this.tbody.innerHTML = str;
83         }
84     }
85     new Car;

上面是用localStorage的方法實現的購物車。

以上是我用兩種方法實現購物車的代碼,效果上是沒有區別的,cookie更為浪費性能一些,可以兩種都試下。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 封裝一個函數 調用函數getColor()就能隨機獲取一個16進位的顏色值 ...
  • 1.Chinese (Simplified) Language Pack for Visual Studio Code——中文語言包 2.Beautify——代碼格式化工具 3.HTML Snippets——H5代碼片段及提示 4.Auto Rename Tag——標簽自動重命名 5.CSS Pee ...
  • JQ基礎——JQ的簡單使用 ...
  • vue.js解決開始代碼載入,以至於亂碼 vue.js通過幾行代碼可以解決這個問題 css: html: 使用後會等vue載入完再呈現效果,就不會出現,代碼在視圖裡了。 順帶介紹幾個基礎的vue api。 綁定css樣式: css: html: v bind:class="{done樣式:這是樣式中 ...
  • VUE從入門到放棄(第一天)——整體流程 先想想一個項目,vue項目是從什麼到什麼,然後再什麼的?那是什麼呢? 1. 搭建 ( vue cli) 2. 代碼內容 3. 運行 4. 封裝 5. 成品 一.搭建(腳手架vue cli) 首先node.js,npm,vue cli(腳手架)一定要有,這裡不 ...
  • 傻瓜式操作搭建個人網站 1.首先買功能變數名稱和雲伺服器 買東西一般都很方便的給錢就行。。。 百度,騰訊,阿裡都可以買,而且只要給錢,啥東西都給的明明白白。 這裡我就不細說了。個人推薦百度的。因為我就是用這個的。 2.後面來說下錢解決不了得事,配置雲伺服器,(買的功能變數名稱先放著不動它) 找到自己買的實例,打開V ...
  • # Vue指令大集合(無slot) #### 包含內容: 1. v-cloak2. v-html3. v-text4. v-bind5. v-show6. v-model7. v-for8. v-if v-else-if v-else9. v-pre 代碼如下:(可以自己複製去看一下) html 展 ...
  • .attr( ) 可以設置元素的屬性(也就是給元素新增加一個原來並不存在的屬性)也可以獲取元素的本來就有的屬性以及額外設置的屬性。如果要獲取的屬性沒有設置,那麼獲取到的結果是 undefined; .prop( )可以設置元素的屬性(HTML固有的屬性,可以給元素添加屬性)也可以獲取元素的固有的屬性 ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...