1 // JavaScript Document2
3 function $(id) {4 return document.getElementById(id);5 }6
7 function $$(name) {8 return document.createElement(name);9 }10
11 window.onload = function() {12 var buys = document.getElementsByClassName(‘product_button‘);13 for(var i = 0 ; i
22 return;23 }24 //添加物品于购物车25 createItem( price.cloneNode(true) , name.cloneNode(true) , img.cloneNode(true) );26 }27 }28
29 }30
31 //判断物品是否存在于购物车中32 function checkIsInCart(name){33 var cart=document.getElementsByClassName(‘items‘);34 for(var i=0;i
41 //创建购物车的元素42 function createItem( price , name , img ) {43 var items= $$(‘div‘);44 items.className= ‘items‘;45 items.appendChild(img);46 items.appendChild(name);47 items.appendChild(price);48 /*创建控制区*/49 var control_span= $$(‘span‘);50 var minus= $$(‘button‘);51 minus.value= ‘-‘52 minus.innerHTML= ‘-‘;53 minus.οnclick= changeItemAmount;54
55 var count= $$(‘input‘);56 count.maxLength= 3;//注意小写maxlength就是错的57 count.value= 1;58 count.οnchange= getItemTotal;59
60 var add= $$(‘button‘);61 add.value= ‘+‘;62 add.innerHTML= ‘+‘;63 add.οnclick= changeItemAmount;64
65 control_span.appendChild(minus);66 control_span.appendChild(count);67 control_span.appendChild(add);68
69 items.appendChild(control_span);70
71 var item_total= $$(‘span‘);72 item_total= price.cloneNode(true);73
74 items.appendChild(item_total);75
76 $(‘cart‘).appendChild(items);77
78 getTotal();79 }80
81 //数量增加或减少所触发的事件82 function changeItemAmount() {83 var type= this.value;// + -84 var amount; //数量框85 //++++++++++++++++++++++++++++++++++++++86 if(type==‘+‘){87 this.previousSibling.previousSibling.disabled=false;88 var amount= this.previousSibling;89 var curr_value= parseInt(amount.value)+ 1;90 amount.value= curr_value;91
92 var price= this.parentNode.previousSibling.firstChild.nodeValue;93 this.parentNode.nextSibling.innerHTML= amount.value* price ;94 }95 //-------------------------------------------96 if(type==‘-‘){97 var amount= this.nextSibling;98 var curr_value= parseInt(amount.value)- 1;99 if(curr_value<0){100 this.disabled=true;101 return;102 }103 amount.value= curr_value;104
105 var price= this.parentNode.previousSibling.firstChild.nodeValue;106 this.parentNode.nextSibling.innerHTML= amount.value* price ;107 }108
109 getTotal();110 }111
112 //数量改变时所触发的事件113 function getItemTotal() {114 var amount= parseInt(this.value) ;115 var price= this.parentNode.previousSibling.firstChild.nodeValue;116 this.parentNode.nextSibling.innerHTML= amount* price ;117 getTotal();118 }119
120 //循环获取购物车的总价121 function getTotal() {122 var cart=document.getElementsByClassName(‘items‘);123 var money=0;124 for(var i=0;i