javascript - 计算值未进入for循环

标签 javascript jquery

我需要计算 var packprice + var packprices + var ala 哪个进入 for 循环。我在控制台中获取了所有值,但在 tprice 中没有获取加法。请帮忙。

$( "#get_total" ).click(function() {
    alert('calculation pending');
    var idSelector = function() { return this.value; };
    var packprices = 0;
    var packprice = 0;
    var c = $(":checkbox:checked").map(idSelector).get();

    for (var i = 0; i < c.length; i++) {
        // console.log(c[i]);
        // console.log(parseInt($(".longduration_price" + c[i]).val()));
        if($(".duration_status" + c[i]).is(':checked'))
        {
            var packprice = !isNaN(parseInt($(".longduration_price" + c[i]).val())) ? parseInt($(".longduration_price" + c[i]).val()) : 0 ;
            console.log(packprice);
        }else{
            var packprices = !isNaN(parseInt($(".packpriceone" + c[i]).val())) ? parseInt($(".packpriceone" + c[i]).val()) : 0 ;
            console.log(packprices); 
        }
        var ala = parseInt($("#alacartprice").val());
        var tprice = packprice + packprices + ala;
    }

    console.log(tprice);

    $("#totalprice").val(tprice);
});

最佳答案

您需要在循环外部声明 tprice 并将结果添加到 tprice 中,如下所示。

$( "#get_total" ).click(function() {
alert('calculation pending');
var idSelector = function() { return this.value; };
var packprices = 0;
var packprice = 0;
var c = $(":checkbox:checked").map(idSelector).get();
var tprice = 0;
for (var i = 0; i < c.length; i++) {
    // console.log(c[i]);
    // console.log(parseInt($(".longduration_price" + c[i]).val()));
    if($(".duration_status" + c[i]).is(':checked'))
    {
        var packprice = !isNaN(parseInt($(".longduration_price" + c[i]).val())) ? parseInt($(".longduration_price" + c[i]).val()) : 0 ;
        console.log(packprice);
    }else{
        var packprices = !isNaN(parseInt($(".packpriceone" + c[i]).val())) ? parseInt($(".packpriceone" + c[i]).val()) : 0 ;
        console.log(packprices); 
    }
    var ala = parseInt($("#alacartprice").val());
    tprice += packprice + packprices + ala;
}

console.log(tprice);

$("#totalprice").val(tprice);
});

关于javascript - 计算值未进入for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54002709/

相关文章:

javascript - 将 React PureComponent 重构为基于钩子(Hook)的功能组件

javascript - 如何在 jQuery 中对文本产生闪光效果?

javascript - 如何将 2015 年 8 月 16 日星期日 00 :00:00 GMT+0200 (W. 欧洲夏令时间) 转换为 16.08.2015

javascript - 使用javascript将wav转换为mp3

javascript - 基于php变量的mysql查询

JavaScript 和 Node.js - Controller 函数中的 JSON 字符串不正确

php - 读取由 PHP 生成的包含 @attributes 的 JSON(使用 jQuery)

jquery - 使用 Jquery .each() 函数隐藏图像,因为另一个图像显示在同一个类中

javascript - jQuery 不会让我做 if block ?

javascript - 添加 'hidden' 类时使 bootstrap div 淡出