var total=0.0; //加 //获取所有+按钮 var increment = document.getElementsByClassName("increase"); for (var i = 0; i < increment.length; i++) { //为a标签添加index属性,用于记录下标 increment[i].index = i; //点击+数量增加的功能函数 increment[i].onclick = function () { var flag = this.index; //获取当前按钮对应的数量框 var q = document.getElementsByClassName("quantity")[flag]; var newvalue = parseInt(q.value) + 1; q.setAttribute('value', newvalue); } } //减 //获取所有-按钮 var decrement=document.getElementsByClassName('decrease'); //点击-数量减少的功能函数 for(var j=0;j<decrement.length;j++) { decrement[j].index=j; decrement[j].onclick=function() { var flag=this.index; //获取当前a标签对应的那个数量框 var q=document.getElementsByClassName("quantity")[flag]; if(parseInt(q.value)>1) { var newvalue=parseInt(q.value)-1; q.setAttribute('value',newvalue); } } }能否根据这个加减写一个小计代码
时间: 2024-02-10 19:05:48 浏览: 166
可以,根据上述加减代码,可以在数量框的HTML代码中添加一个小计标签,然后在加减按钮的点击函数中,根据当前数量框的值和商品单价计算小计,并将小计的值设置为小计标签的文本内容。以下是示例代码:
HTML代码:
```html
<div class="item">
<span class="name">商品名称</span>
<span class="price">商品单价</span>
<div class="quantity-wrapper">
<a href="#" class="decrease">-</a>
<input type="text" class="quantity" value="1">
<a href="#" class="increase">+</a>
</div>
<span class="subtotal">小计</span>
</div>
```
JavaScript代码:
```javascript
var increment = document.getElementsByClassName("increase");
var decrement = document.getElementsByClassName("decrease");
var quantity = document.getElementsByClassName("quantity");
var price = document.getElementsByClassName("price");
var subtotal = document.getElementsByClassName("subtotal");
for (var i = 0; i < increment.length; i++) {
increment[i].index = i;
increment[i].onclick = function() {
var flag = this.index;
var q = quantity[flag];
var p = price[flag].textContent;
var s = subtotal[flag];
var newvalue = parseInt(q.value) + 1;
q.setAttribute("value", newvalue);
s.textContent = (newvalue * parseFloat(p)).toFixed(2);
calculateTotal();
};
}
for (var j = 0; j < decrement.length; j++) {
decrement[j].index = j;
decrement[j].onclick = function() {
var flag = this.index;
var q = quantity[flag];
var p = price[flag].textContent;
var s = subtotal[flag];
if (parseInt(q.value) > 1) {
var newvalue = parseInt(q.value) - 1;
q.setAttribute("value", newvalue);
s.textContent = (newvalue * parseFloat(p)).toFixed(2);
calculateTotal();
}
};
}
function calculateTotal() {
var total = 0.0;
for (var k = 0; k < subtotal.length; k++) {
total += parseFloat(subtotal[k].textContent);
}
document.getElementById("total").textContent = total.toFixed(2);
}
```
这段代码实现了商品数量的加减以及每个商品的小计计算,同时还有一个总计的计算函数。注意,需要将每个商品的单价在HTML代码中设置为一个文本节点,例如`<span class="price">10.00</span>`,这样在JavaScript代码中才能通过`textContent`属性获取到它的值。小计和总计需要在计算时进行四舍五入,保留两位小数,可以使用`toFixed`方法实现。
阅读全文