1. What is the underlying principle of the shopping cart? How can the statistics be completed?
2. Use function parameters to create the first half. How to implement the second half?
3. The code is as follows:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>网页标题</title>
<style>
li{margin-top:20px;}
</style>
<script>
window.onload = function (){
var box = document.getElementById("box");
var aLi = box.getElementsByTagName("li");
//var oU = document.getElementsByTagName("u");
function fn(li){
var aBtn = li.getElementsByTagName("input");
var oSpan =li.getElementsByTagName("span")[0];
var oI = li.getElementsByTagName("i")[0];
var oB = li.getElementsByTagName("b")[0];
aBtn[1].onclick = function(){
oSpan.innerHTML++;
oB.innerHTML = oSpan.innerHTML*oI.innerHTML;
}
aBtn[0].onclick = function(){
if(oSpan.innerHTML>0){
oSpan.innerHTML--;
}
oB.innerHTML = oSpan.innerHTML*oI.innerHTML;
}
}
for(var i=0;i<aLi.length;i++){
fn(aLi[i]);
//
}
}//js最后执行
</script>
</head>
<body>
<ul id="box">
<li>
<input type="button" value="-">
<span>0</span>
<input type="button" value="+">
单价:<i>10</i>元
小计:<b>0</b>元
</li>
<li>
<input type="button" value="-">
<span>0</span>
<input type="button" value="+">
单价:<i>7.5</i>元
小计:<b>0</b>元
</li>
<li>
<input type="button" value="-">
<span>0</span>
<input type="button" value="+">
单价:<i>15</i>元
小计:<b>0</b>元
</li>
<li>
<input type="button" value="-">
<span>0</span>
<input type="button" value="+">
单价:<i>20</i>元
小计:<b>0</b>元
</li>
<li>
<input type="button" value="-">
<span>0</span>
<input type="button" value="+">
单价:<i>150</i>元
小计:<b>0</b>元
</li>
</ul>
</body>
</html>
The following part: There are n pieces of products in total, the unit price of the most expensive product is a yuan, and how to write the part that costs b yuan in total?
How to assign values to variables and count the final sum of data?
(code and pictures have been pasted)
I’ll post all the code. Take a look
It’s perfect to write a shopping cart using object-oriented methods. The following is the es6 code
It is best to add hook functions (onSave, onAdd, onRemove....) to each method to achieve reuse and decoupling
The principle is that when the user clicks the plus sign on the product selection page, the data is obtained from the data source and put into a new array
Then get a new array object, which is the shopping cart list.
Statistics is to add up the price fields in the array object. As for the method you use to add up, it depends on your preference. I use reduce.
If there is a minus sign, there must also be a corresponding subtraction operation.