js+cookie购物车,添加商品和查看购物车列表
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>商品列表</title> <style> span{ padding:10px; } li{ list-style: none; } li span{ width:150px; display: inline-block; text-align: center; } </style> <script src="../tools.js"></script> </head> <body> <div id="list"> <ul> <li><span>编号</span><span>名称</span><span>单价</span><span><a href="javascript:0">操作</a></span></li> <li><span>1</span><span>绿箭</span><span>15</span><span><a href="javascript:0">添加购物车</a></span></li> <li><span>2</span><span>中华牙膏</span><span>19</span><span><a href="javascript:0">添加购物车</a></span></li> <li><span>3</span><span>小熊毛巾</span><span>39</span><span><a href="javascript:0">添加购物车</a></span></li> <li><span>4</span><span>枫叶手机</span><span>56</span><span><a href="javascript:0">添加购物车</a></span></li> <li><span>5</span><span>儿童手表</span><span>2400</span><span><a href="javascript:0">添加购物车</a></span></li> <li><span>6</span><span>植物唇膏</span><span>36</span><span><a href="javascript:0">添加购物车</a></span></li> </ul> </div> <p> <a href="cartList.html"target="_blank">查看购物车</a> </p> <script> // 把事件委托给父级 tools.on(tools.$("#list"),"click",function(e){ e=e||window.event; var target = e.target || e.srcElement; if(target.className === "addMe"){ //获取选中得内容 var li = target.parentNode.parentNode; var obj={ id:li.children[0].innerHTml, name:li.children[1].innerHTml, price:li.children[2].innerHTml, num:1 }; // 判断有无,存进cookie var arr = tools.cookie("cart")?JSON.parse(tools.cookie("cart")):[]; var index; var isExist = arr.some(function(item,i){ //some满足条件返回true,查找结束 index = i; return item.id === obj.id; }) if(isExist){ arr[index].num++; }else{//不满足条件就添加进数组 arr.push(obj); } } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="../tools.js"></script> <style> *{ margin:0; padding:0; font-size:14px} #box{ width:500px; margin:100px auto} table,th,td{ border:1px solid #000; border-collapse:collapse} td,th{ width:100px; height:30px; padding:10px} input[type="text"]{ display:none; height:24px; width:60px; border:1px solid #ccc;} tbody tr td:first-child{text-align: center;} tfoot td{text-align: right;} .editBtn{ color:#666} .delBtn{ color:red} .okBtn,.cancelBtn{ display:none} .edit span{ display:none} .edit input[type="text"]{ display:inline-block} .edit .editBtn,.edit .delBtn{ display:none} .edit .okBtn,.edit .cancelBtn{ display:inline} </style> </head> <body> <div id="box"> <table> <thead> <tr> <th><label>全选:<input type="checkbox" id="allCheck"/></label></th> <th>编号</th> <th>名称</th> <th>单价</th> <th>数量</th> <th>编辑</th> </tr> </thead> <tbody> <!--<tr> <td><input type="checkbox" class="check"/></td> <td><span>张三</span><input type="text"></td> <td><span>18</span><input type="text"></td> <td><span>1</span><input type="text"></td> <td> <a href="javascript:;" class="editBtn">编辑</a> <a href="javascript:;" class="okBtn">确定</a> <a href="javascript:;" class="cancelBtn">取消</a> <a href="javascript:;" class="delBtn">删除</a> </td> </tr>--> </tbody> <tfoot> <tr> <td colspan="6">总价:¥<b id="money"></b></td> </tr> </tfoot> </table> </div> <script> var box = tools.$("#box"); var table = tools.$("table",box)[0]; var tbody = tools.$("tbody",box)[0]; // 通过cookie拼接购物车 var arr = JSON.parse(tools.cookie("cart")); var str = ""; for(var a of arr){ str += \'<tr>\'+ \'<td><input type="checkbox" class="check"/></td>\'+ \'<td>\'+a.id+\'</td>\'+ \'<td><span>\'+a.name+\'</span></td\', \'<td><span>\'+a.price+\'</span></td>\', \'<td><span>\'+a.num+\'</span></td>\', \'<td>\'+ \'<a href="javascript:;" class="editBtn">编辑</a>\'+ \'<a href="javascript:;" class="editBtn">确定</a>\'+ \'<a href="javadcript:;"\' \'</td>\'+ \'</tr>\'; } tbody.innerHTML = str; var allCheck = tools.$("#allCheck"); var n=0; table.onclick = function(e){ e = e||event; var target=e.target||e.srcElement; var tr = target.parentNode.parentNode; if(target.className ="editBtn"){ tr.className="edit"; var aSpan = tools.$("span",tr); for(var i=0;i<aSpan.length;i++){ aSpan[i].nextElementSibling.value = aSpan[i].innerHTML; } }else if(target.className === "okBtn"){ tr.className = ""; var aSpan = tools.$("span",tr); for(var i= 0 ;i<aSpan.length;i++){ aSpan[i].innerHTML=aSpan[i].nextElementSibling.value; } }else if(target.className === "cancelBtn"){ // 取消 tr.className = ""; }else if(target.className === "delBtn"){ if(confirm("确定删除?")){ tr.parentNode.removeChild(tr); var check = tools.$(".check",tr)[0]; if(check.checked) n--; allCheck.checked = (n===tools.$(".check",box).length); calcPrice(); } } else if(target.id === "allcheck"){ // 全选 var aCheck = tools.$(".check",box); for(var i = 0;i<aCheck.length;i++){ aCheck[i].checked = target.checked; } n = target.checked?aCheck.length : 0; calcPrice(); }else if(target.className === "check"){ target.checked ? n++ : n--; var aCheck = tools.$(".check",box); allCheck.checked = n === aCheck.length; calcPrice(); } } function calcPrice(){ var sum = 0; var aTr = tools.$("tr",tbody); for(var j=0;j<aTr.length;j++){ if(tools.$(".check",aTr[j])[0].checked){ var price = Number(tools.$("span",aTr[j])[1].innerHTML); var num = Number(tools.$("span"),aTr[j][2].innerHTML); sum += price*num; } } tools.$("#money").innerHTML = sum + "元"; } </script> </body> </html>
// tools.js/文件 var tools = { /* 查找DOM对象 * @param selector string css基本选择器 * @param [parent] DOMobj 父级元素对象 * @return DOMobj || HTMLCollection */ $: function(selector ,parent){ parent = parent || document; switch(selector.charAt(0)){ case "#": return document.getElementById(selector.slice(1)); case ".": return parent.getElementsByClassName(selector.slice(1)); default: return parent.getElementsByTagName(selector); } }, /*获取外部样式 * @param obj DOMobj 要获取属性的DOM对象 * @param attr string 获取某一条属性的属性名 * @return string obj的attr属性值 */ getStyle: function(obj, attr){ if(obj.currentStyle){ //针对IE return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr]; } }, /* 获取body宽高 * * @return obj {width,height} * */ getBody: function(){ return { width: document.documentElement.clientWidth || document.body.clientWidth, height: document.documentElement.clientHeight || document.body.clientHeight }; }, /*让元素在body里绝对居中 * @param obj DOMobj 居中的那个元素对象 */ showCenter: function(obj){ //console.log(this); //this在不同执行环境指向的对象是不一样的,所以用一个变量在指向变化之前先存下来 var _this = this; //obj相对于body定位 document.body.appendChild(obj); obj.style.position = "absolute"; function center(){ //console.log(_this); var _left = (_this.getBody().width - obj.offsetWidth)/2, _top = (_this.getBody().height - obj.offsetHeight)/2; obj.style.left = _left + "px"; obj.style.top = _top + "px"; } center(); window.onresize = center; }, /* 获取和设置样式 * @param obj DOMobj 设置谁的样式 * @param oAttr obj {left:"200px",top:"100px"} 设置css * @param oAttr string 获取属性值 @return string oAttr对应的属性值 * */ css: function(obj,oAttr){ if(typeof oAttr === "string"){ return obj.style[oAttr]; }else{ for(var key in oAttr){ obj.style[key] = oAttr[key]; } } }, /*添加事件监听 * @param obj DOMobj 添加事件的DOM元素 * @param type string 事件句柄 * @param fn Function 事件处理函数 * */ on: function(obj, type, fn){ //兼容判断 if(window.attachEvent){ obj.attachEvent("on"+type, fn); }else{ obj.addEventListener(type, fn, false); //第三个参数指是否捕获,默认是false } }, /*移除事件监听 * @param obj DOMobj 添加事件的DOM元素 * @param type string 事件句柄 * @param fn Function 事件处理函数 * */ off: function(obj, type, fn){ window.detachEvent ? obj.detachEvent("on"+type, fn) : obj.removeEventListener(type, fn, false); }, /* 存取cookie * @param key string cookie的名称 * @param [value] string cookie的值 如果不传,获取cookie * @param [exp] object {expires:3,path:"/"} * */ cookie: function(key, value, exp){ //判断value是否有效 if(value === undefined){ //获取 var obj = new Object(); var str = document.cookie; var arr = str.split("; "); for(var i = 0; i < arr.length; i++){ var item = arr[i].split("="); obj[item[0]] = item[1]; } //判断有没有取到 return obj[key] ? decodeURIComponent(obj[key]) : undefined; }else{ //拼接expires var str = ""; if(exp){ //如果传了过期时间 if(exp.expires){ //设置new Date到过期的那一天 var d = new Date(); d.setDate(d.getDate()+exp.expires); str += ";expires="+d; } //如果传了path if(exp.path){ str += ";path="+exp.path; } } document.cookie = key+"="+encodeURIComponent(value)+str; } } }
以上,就是我用js写的添加购物车以及查看购物车的代码,比较简单。用的存取cookie的方式
版权声明:本文为orange-cccc原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。