【问题标题】:.js variables not returning to zero when made equal to 0.js 变量在等于 0 时不返回零
【发布时间】:2018-01-18 09:24:22
【问题描述】:

我有各种 .js 函数来计算模式中的订单小计、税收和最终总价。计算是正确的,但是在模态退出/模态弹出窗口中似乎没有清除变量。这意味着第一个之后的每个模态都只是将它们的(正确)计算添加到之前的计算中,而不是像我试图让它那样从零开始。

我在 .js 源代码中设置了断点,它告诉我 .js 数字是不归零的,即使在数字传回后立即设置为零也是如此。

这里是第一个和第二个模态调用的图片集来说明这个问题(右下角的数字):

这是我的 html,以防它实际上是基于标签的问题:

@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/_Layout.cshtml";
}
<div class="col-sm-3">&nbsp;</div>
<div class="panel col-sm-6 col-xs-12">
    <div class="panel-title text-center" style="padding-top:20px;">
        <h3 style="font-weight:bolder">Cart Contents</h3>
        <img src="/img/cart.png" style="height:10%;width:10%;padding-bottom:5%;" />
    </div>
    <div class="text-center" style="padding-top:10px;">
        @{
            Dictionary<string, object> cart = Context.Session.Get<Dictionary<string, Object>>("cart");
            decimal itemSubTotal = 0;
            decimal subTotal = 0;
            decimal itemTaxTotal = 0;
            decimal taxTotal = 0;
            decimal salesTaxRate = 0.13M; //m required for a literal
            decimal orderTotal = 0;



        }
        <table class="table table-striped">
            <tr style="font-weight:bolder;">

                <th class="col-xs-2 text-center">Product Code</th>
                <th class="col-xs-2 text-center">Qty</th>
                <th class="col-xs-2 text-center">Item Name</th>
                <th class="col-xs-2 text-center">Price</th>
            </tr>
            @{
                if (cart != null)
                {

                    foreach (var key in cart.Keys)
                    {
                        ProductViewModel item = JsonConvert.DeserializeObject
                        <ProductViewModel>
                        (Convert.ToString(cart[key]));

                        if (item.Qty > 0)
                        {

                            subTotal += item.MSRP * item.Qty;


                            <tr>
                                <td class="col-xs-2 text-center">@item.Id</td>
                                <td class="col-xs-2 text-center">@item.Qty</td>
                                <td class="col-xs-2 text-left">@item.ProductName</td>
                                <td class="col-xs-2 text-center">@string.Format("{0:C}", @item.MSRP)</td>
                            </tr>

                        }
                    }

                    taxTotal += Decimal.Multiply(subTotal, salesTaxRate);
                    orderTotal += subTotal + taxTotal;
                }
            }
        </table>
        <hr />
        <table class="table table-striped">
            <tr>
                <th colspan="4" class="col-xs-4 text-left" style="font-size:large;font-weight:bold;">
                    Cart
                    Totals
                </th>
            </tr>
            <tr>
                <td class="col-xs-2 text-right">Subtotal: </td>
                <td class="col-xs-4 text-left" id="subtotal">@string.Format("{0:C}", @subTotal)</td>
            </tr>
            <tr>
                <td class="col-xs-2 text-right">Tax Total: </td>
                <td class="col-xs-4 text-left" id="taxtotal">@string.Format("{0:C}", @taxTotal)</td>
            </tr>
            <tr>
                <td class="col-xs-2 text-right">Order Total: </td>
                <td class="col-xs-4 text-left" id="ordertotal">@string.Format("{0:C}", @orderTotal)</td>
            </tr>
            @{ 
                @subTotal = 0;
                @taxTotal = 0;
                @orderTotal = 0;
            }
        </table>
        <div class="text-center">
            <form asp-controller="Cart" asp-action="AddCart" method="post" role="form">
                @if (Context.Session.GetString(SessionVars.User) != null)
                {
                    <button type="submit" class="btn btn-sm btn-primary" id="modalbtn">Add Cart</button>
                }
                &nbsp;<a href="/Cart/ClearCart" class="btn btn-sm btn-success">Clear Cart</a>
            </form>
        </div>
    </div>
  </div>

这是进行计算的 .js 文件:

   var link = '/GetOrders';
    var detailslink = '/GetOrderDetails/';
    var subtotal = 0;
    var finalPrice = 0;
    var taxAmount = 0;
    // register modal component
Vue.component('modal', {
    template: '#modal-template',
    props: {
        item: {},
        modalItem: {},
        details: []
    },
})
new Vue({
    el: '#orders',
    methods: {
        GetOrders: function () {
            var self = this
            axios.get(link).then(function (response) {
                self.orders = response.data;

            }, function (error) {
                console.log(error.statusText);
            });
        },
        loadAndShowModal: function () {
            var self = this
            axios.get(detailslink + this.modalItem.id).then(function (response) {
                self.details = response.data;
                self.showModal = true;
            }, function (error) {
                console.log(error.statusText);
            });
        },
    },
    mounted: function () {
        this.GetOrders();
    },
    data: {
        orders: [],
        showModal: false,
        modalItem: {},
        details: []
    }
});
function formatDate(date) {
    var d;
    if (date === undefined) {
        d = new Date(); //no date coming from server
    }
    else {
        var d = new Date(Date.parse(date)); // date from server
    }
    var _day = d.getDate();
    var _month = d.getMonth() + 1;
    var _year = d.getFullYear();
    var _hour = d.getHours();
    var _min = d.getMinutes();
    if (_min < 10) { _min = "0" + _min; }
    return _year + "-" + _month + "-" + _day + " " + _hour + ":" + _min;
}


function calcLinePrice(qtySold, msrp)
{

    var linePrice = qtySold * msrp;
    subtotal += linePrice;
    finalPrice += linePrice;
    return linePrice.toFixed(2);

    finalPrice = 0;
    subtotal = 0;

}

function calcSubtotal()
{

    return subtotal.toFixed(2);
    subtotal = 0;

    finalPrice = 0;
    subtotal = 0;
}

function calcTax() {

    taxAmount = finalPrice * 0.13

    return taxAmount.toFixed(2);
    taxAmount = 0;

}


function calcFinalPrice() {
    var total = 0;
    total = finalPrice + taxAmount;
    return total.toFixed(2);

    finalPrice = 0;
    subtotal = 0;

}

如您所见,我在每次计算中都将 finalTotal 和 subtotal 归零,以试图解决这个问题。似乎无论我做什么,除了页面重新加载之外,他们拒绝归零。有什么帮助吗?

编辑:我试图在错误的点归零。我通过将我的 calcFinalPrice() 函数(作为最后一个函数)更改为这个来解决这个问题:

function calcFinalPrice() {
    var total = 0;
    total = finalPrice + taxAmount;
    taxAmount = 0;
    subtotal = 0;
    finalPrice = 0;
    return total.toFixed(2);


}

【问题讨论】:

  • 检查浏览器开发者工具控制台(这是调试 101) - 你应该看到一条消息告诉你你做错了什么 - 提示,它与你的 return 在函数中的位置有关声明是
  • 当前上下文中return语句后不会执行任何代码
  • @JaromandaX 我知道,我正在使用它来查找 .js 中变量的值,以确认这是 .js 问题而不是标签问题。感谢您的提示,我没有意识到 js 函数在返回后不会继续在内部处理。
  • 我在谈论unreachable code after return statement 中的消息 - 而不是您的console.log 消息:p ...没关系,似乎 firefox 是唯一提供此有用消息的浏览器
  • 这实际上是非常有用的信息,我没有意识到它会有额外的错误检查功能。也许我现在也会尝试在 Firefox 中调试作为我的过程的一部分。

标签: javascript html twitter-bootstrap vue.js vue-component


【解决方案1】:

您在将“0”重新分配给变量之前返回。重新分配值后使用 return。

【讨论】:

  • 是的,但是如果为下一个模态清除它的唯一方法是在返回之前将其归零,我该如何传回计算值?我尝试在函数开头创建一个我为零的持有人变量,但现在持有人变量也有同样的问题。
  • 不要使用全局变量,而是使用道具,这会有所帮助。 :)
猜你喜欢
  • 1970-01-01
  • 2011-03-09
  • 2012-02-26
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
相关资源
最近更新 更多