利用现有代码创建多个功能

时间:2019-03-26 18:35:07

标签: javascript html function

我的代码可以工作,但是我需要从中创建多个函数,每次创建一个函数时,它就会弄乱逻辑并抛出表

我需要创建以下功能:

calculateTax(); , calculateShipping(); calculateGrandTotal();

基本上:

function calculateTax(subtotal, rate) {
    var tax = subtotal * rate;
}

function calculateShipping(subtotal, threshold) {
    shipping = 40;
    if (subtotal > 1000)
        threshold = 1000;
        shipping = 0;
}

function calculateGrandTotal(subtotal,tax,shipping) {
     var grandTotal = subtotal + tax + shipping;
}

结果应该像这样:enter image description here

我的代码(有效):

function calculateTotal(quantity, price) {

return quantity * price;

}

window.onload = () => {

var rate = 0.10;
var threshold = 1000;
var subtotal = 0;
var product_total = 0;
var subtotal = 0;


for (let i = 0; i < filenames.length; i++) {

subtotal += calculateTotal(quantities[i], prices[i]);

outputCartRow(filenames[i], titles[i], quantities[i], prices[i], calculateTotal(quantities[i], prices[i]));

}

var tax = subtotal * 0.10;

var shipping = 40;

if (subtotal > 1000)

shipping = 0;

var grandTotal = subtotal + tax + shipping;

document.getElementsByTagName("tbody")[0].innerHTML +=

`<tr class="totals">

<td colspan="4">Subtotal</td>

<td>$${subtotal.toFixed(2)}</td>

</tr>

<tr class="totals">

<td colspan="4">Tax</td>

<td>$${tax.toFixed(2)}</td>

</tr>

<tr class="totals">

<td colspan="4">Shipping</td>

<td>$${shipping.toFixed(2)}</td>

</tr>

<tr class="totals focus">

<td colspan="4">Grand Total</td>

<td>$${grandTotal.toFixed(2)}</td>

</tr>`;

}

但是,如果我尝试这样做(以tax函数为例)

var tax = calculateTax();


for (let i = 0; i < filenames.length; i++) {

subtotal += calculateTotal(quantities[i], prices[i]);

outputCartRow(filenames[i], titles[i], quantities[i], prices[i], calculateTotal(quantities[i], prices[i]));

}
function calculateTax(subtotal, rate){
    tax = subtotal * 0.10;
    var shipping = 40;
    if (subtotal > 1000)
    shipping = 0;
}

它除去了小计,税款,运费和总计的底盒 enter image description here

不知道如何摆脱框框的限制,如何创建这些功能。

1 个答案:

答案 0 :(得分:0)

您必须将每行的html代码分别添加到每个函数中,然后调用它们以使底部框正确显示。

function calculateTax(subtotal, rate){
    tax = subtotal * 0.10;
    var shipping = 40;
    if (subtotal > 1000)
    shipping = 0;
    document.getElementsByTagName("tbody")[0].innerHTML +=
    '<tr class="totals">

    <td colspan="4">Tax</td>

    <td>$${tax.toFixed(2)}</td>

    </tr>'
}