Cookie和JS购物车的简单实例

简介:

最近学原生的Javascript,需要弄个购物车的功能,下面是利用cookie做的一个演示

思路其实很简单,商品界面通过value获取对应的值,然后把这个商品的各种信息放入一个字典;因为有多个商品,把这些商品的字典对象都放在一个数组里面就行了。然后通过JSON序列化这个这个数组,保存在cookie里面。在购物车界面通过读取cookie获取这些信息,然后动态地创建一个表格显示即可。



商品界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<!DOCTYPE html>
<html lang= "en" >
<head>
<meta charset= "UTF-8" >
<title>购物页面</title>
<style>
ul{list-style:none;padding:0;margin:0;}
.goods li{display:inline-block;border:1px solid  #ddd;padding:10px;margin:10px;}
.goods li:hover{background-color: #efefef;}
.goods .price{color: #f00;font-weight:bold;}
.goods .price::before{
content: "¥" ;
}
</style>
<script>
window.onload =  function (){
     var  goods = document.getElementsByClassName( 'goods' )[0];
     // 用于保存购物车商品信息
     var  carList = [];
     // 先获取当前cookie
     var  cookies = document.cookie.split( '; ' );
     for ( var  i=0;i<cookies.length;i++){
         var  arr = cookies[i].split( '=' );
         if (arr[0] ===  'carlist' ){
             carList = JSON.parse(arr[1]);
         }
     }
// 事件委托
     goods.|| window.event;
         var  target = e.target || e.srcElement;
         // 添加到购物车
         if (target.tagName.toLowerCase() ===  'button' ){
         // 获取当前li (Li-div-button)
         var  currentLi = target.parentElement.parentElement;
         var  children = currentLi.children;
         var  currentGUID = currentLi.getAttribute( 'data-guid' );
         // 先创建一个对象保存当前商品信息
         var  goodsObj = {};
         goodsObj.guid = currentGUID;
         goodsObj.qty = 1;
         goodsObj.name = children[1].innerHTML;
         goodsObj.price = children[2].innerHTML;
         goodsObj.imgUrl = children[0].src;
         // 如果cookie为空,则直接添加
         if (carList.length===0){
         // 添加到carList
         carList.push(goodsObj);
         } else {
         // 先判断cookie中有无相同的guid商品
             for ( var  i=0;i<carList.length;i++){
             // 如果商品已经存在cookie中,则数量+1
                 if (carList[i].guid === currentGUID){
                     carList[i].qty++;
                     break ;
                 }
             }
     // 如果原cookie中没有当前商品
         if (i===carList.length){
         // 添加到carList
         carList.push(goodsObj);
         }
         }
         // 存入cookie
         // 把对象/数组转换诚json字符串:JSON.stringify()
         document.cookie =  'carlist='  + JSON.stringify(carList);
         }
     }
}
</script>
</head>
<body>
     <ul class= "goods" >
         <li data-guid= "g01" >
             <img src= "img/02.jpg" >
             <p>货物1</p>
             <p class= "price" >98.88</p>
             <div class= "add2cart" >
                 <button onclick= "Favor(this);" >添加到购物车</button>
             </div>
         </li>
         <li data-guid= "g02" >
             <img src= "img/03.jpg" >
             <p>货物2</p>
             <p class= "price" >88.88</p>
             <div class= "add2cart" >
                 <button onclick= "Favor(this);" >添加到购物车</button>
             </div>
         </li>
         <li data-guid= "g03" >
             <img src= "img/04.jpg" >
             <p>货物3</p>
             <p class= "price" >9.98</p>
             <div class= "add2cart" >
                 <button onclick= "Favor(this);" >添加到购物车</button>
             </div>
         </li>
         <li data-guid= "g04" >
             <img src= "img/05.jpg" >
             <p>货物4</p>
             <p class= "price" >8.88</p>
             <div class= "add2cart" >
                  <button onclick= "Favor(this);" >添加到购物车</button>
             </div>
         </li>
     </ul>
     <a href= "a2.html" >去结算</a>
</body>
<script>
          function  Favor(ths){
             // ths => this => 当前触发事件的标签
             var  top = 49;
             var  left = 71;
             var  op = 1;
             var  fontSize = 18;
             var  tag = document.createElement( 'span' );
             tag.innerText =  '+1' ;
             tag.style.position =  'absolute' ;
             tag.style.top = top +  "px" ;
             tag.style.left = left +  "px" ;
             tag.style.opacity = op;
             tag.style.fontSize = fontSize +  'px' ;
             ths.parentElement.appendChild(tag);
             var  interval = setInterval( function (){
                 top -= 10;
                 left += 10;
                 fontSize += 5;
                 op -= 0.1;
                 tag.style.top = top +  "px" ;
                 tag.style.left = left +  "px" ;
                 tag.style.opacity = op;
                 tag.style.fontSize = fontSize +  'px' ;
                 if (op <= 0.2){
                     clearInterval(interval);
                     ths.parentElement.removeChild(tag);
                 }
             }, 50);
         }
</script>
</html>


wKiom1kbyLjCuA7ZAAEOo9zU3hw409.jpg




购物车的界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
<!DOCTYPE html>
<html lang= "en" >
<head>
<meta charset= "UTF-8" >
<title>购物车</title>
<style>
#carList li{position:relative;padding-bottom:15px;margin-bottom:15px;border-bottom:1px solid #ddd;}
#carList img{display:block;width:100px;}
  .btn-close{padding:0 5px;cursor: default ;}
.btn-close:hover{background-color: #f00;color:#fff;}
.subPrice{padding:5px 20px;color: #f00;font-weight:bold;text-align:right;}
#carList .price{color:#f00;}
table
{
     margin-left: auto;
     margin-right: auto;
}
.price::before{
content: '¥' ;
font-size:11px;
}
/* Table Head */
/* Table Head */
#mytable th {
background-color: rgb(156, 186, 95);
color:  #fff;
border-bottom-width: 1px;
}
/* Column Style */
#mytable td {
color:  #000;
}
/* Heading and Column Style */
#mytable tr {
border-width: 1px;
border-style: solid;
border-color: rgb(156, 186, 95);
}
/* Padding and font style */
#mytable td {
padding: 5px 10px;
font-size: 12px;
font-family: Verdana;
font-weight: bold;
}
#carList .price span{font-size:11px;}
</style>
<script>
window.onload =  function (){
/*
读取cookie中的carlist
把json字符串转换成对象/数组:JSON.parse()
json字符串格式:
1.必须用双引号
2.不能右注释
*/
var  oCarList = document.getElementById( 'carList' );
var  oSubPrice = oCarList.nextElementSibling;
var  btnClear = document.getElementById( 'btnClear' );
var  carList;
var  cookies = document.cookie.split( '; ' );
for ( var  i=0;i<cookies.length;i++){
var  arr = cookies[i].split( '=' );
if (arr[0] ===  'carlist' ){
console.log(JSON.parse(arr[1]));
carList = JSON.parse(arr[1]);
}
}
var  subPrice = 0;
     //动态的根据cookie的内容创建列表
if (carList){
     var  tableRef = document.getElementById( 'mytable' ).getElementsByTagName( 'tbody' )[0];
     console.log(tableRef);
             // Insert a row in the table at the last row
     for ( var  i=0;i<carList.length;i++) {
         //插入一行
         var  newRow = tableRef.insertRow(tableRef.rows.length);
         newRow.setAttribute( 'data-guid' ,carList[i].guid)
         //插入4列
         var  cell0 = newRow.insertCell(0);
         var  cell1 = newRow.insertCell(1);
         var  cell2 = newRow.insertCell(2);
         var  cell3 = newRow.insertCell(3);
         var  cell4 = newRow.insertCell(4);
         // Append a text node to the cell
         var  title = document.createTextNode(carList[i].name);
         cell0.appendChild(title);
         var  price = document.createTextNode(carList[i].price);
         cell1.appendChild(price);
         var  number=document.createTextNode(carList[i].qty);
         cell2.appendChild(number)
         var  img = document.createElement( 'img' );
         img.src = carList[i].imgUrl;
         cell3.appendChild(img)
         var  btnClose = document.createElement( 'span' );
         btnClose.innerHTML =  '删除' ;
         btnClose.className =  'btn-close' ;
         cell4.appendChild(btnClose)
     // 计算总价
         subPrice += carList[i].price*carList[i].qty;
//        li.appendChild(title);
//        li.appendChild(price);
//        li.appendChild(img);
//        li.appendChild(btnClose);
//        ul.appendChild(li);
     }
     // 写入页面
//    oCarList.appendChild(ul);
     // 写入总价
     // toFixed(n)获取小数点后n位(自动四舍五入,Number类型的方法)
oSubPrice.innerHTML =  '<span class="price">'  + subPrice.toFixed(2) +  '</span>' ;
}
// 删除商品
oCarList.|| window.event;
var  target = e.target || e.srcElement;
// 是否点击了删除按钮
if (target.className ===  'btn-close' ){
var  currentLi = target.parentElement.parentElement;
var  currentGUID = currentLi.getAttribute( 'data-guid' );
// 删除cookie中对应的商品
// 根据guid取对比
for ( var  i=0;i<carList.length;i++){
// 找出要删除的商品
if (carList[i].guid === currentGUID){
carList.splice(i,1);
break ;
}
}
// 更新cookie
document.cookie =  'carlist='  + JSON.stringify(carList);
// 删除li节点
currentLi.parentElement.removeChild(currentLi);
location.reload()
}
}
// 清空购物车
// 1、删除DOM节点
// 2、删除cookie
btnClear.onclick =  function (){
oCarList.innerHTML =  '' ;
oSubPrice.innerHTML =  '' ;
// 利用设置有效期位过期事件来达到删除cookie的效果
var  now =  new  Date();
now.setDate(now.getDate()-7);
document.cookie =  'carlist=xx;expires='  + now;
}
}
</script>
</head>
<body>
<h1>我的购物车</h1>
<div id= "carList" >
     <table id= "mytable"   width= "100%"  >
     <th>商品信息</th>
     <th>单价</th>
     <th>数量</th>
     <th>照片</th>
     <th>操作</th>
     <tbody>
     </tbody>
     </table>
</div>
<div class= "subPrice" ></div>
<a href= "#"  id= "btnClear" >清空购物车</a>
<a href= "index.html" >继续购物</a>
</body>
</html>

wKioL1kbyLnBsHN6AADbO8Cconc503.jpg



cookie的内容


wKiom1kbyaejN8B1AACyL4WOf0I389.jpg






本文转自 beanxyz 51CTO博客,原文链接:http://blog.51cto.com/beanxyz/1926569,如需转载请自行联系原作者

目录
相关文章
|
1月前
|
JavaScript
当当网上书店购物车——JS源码
当当网上书店购物车——JS源码
14 0
|
3月前
|
JavaScript
|
4月前
|
机器学习/深度学习 存储 JavaScript
正则表达式基础语法与Java、JS使用实例
正则表达式基础语法与Java、JS使用实例
72 1
|
3月前
|
存储 JavaScript 前端开发
js中session、cookie、 localStorage和SessionStorage的区别和特点
js中session、cookie、 localStorage和SessionStorage的区别和特点
|
8天前
|
存储 JavaScript 前端开发
JavaScript DOM 操作:解释一下 cookie、sessionStorage 和 localStorage 的区别。
Cookie是服务器发送至客户端的文本信息,会随每个请求发送回服务器,适合控制会话状态但可能暴露隐私。SessionStorage仅在当前会话中存储数据,关闭浏览器后清除,适合临时存储如登录状态。LocalStorage则持久保存数据,即使关闭浏览器也不会清除,适用于存储长期设置。三种方式各有侧重,应按需求选择。
12 0
|
11天前
|
JavaScript 前端开发
【掰开揉碎】JavaScript状态机的应用场景与实例(二)
【掰开揉碎】JavaScript状态机的应用场景与实例(二)
|
11天前
|
前端开发 JavaScript 测试技术
【掰开揉碎】JavaScript状态机的应用场景与实例(一)
【掰开揉碎】JavaScript状态机的应用场景与实例(一)
|
12天前
|
JavaScript
|
1月前
|
JavaScript 前端开发
购物车的功能——JS源码
购物车的功能——JS源码
14 2
|
3月前
|
JavaScript 前端开发
js实现购物车效果
js实现购物车效果
23 0