<!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的方式
