处理数值时出现奇怪的JS问题

Strange JS issue while working with numeric values

本文关键字:JS 问题 处理      更新时间:2023-09-26

其想法是每次选中复选框时都刷新总值。

我的HTML看起来像

<table class="table table-striped table-bordered table-hover">

                                <tbody>
...
                                <tr>
                                    <td><input type="checkbox" name="services[]" value="5" class="services"></td>
                                    <td>Sample</td>
                                     <td id="srv_5">60</td>
                                    </tr> 
 ...                    
</tbody>
                        </table>

功能看起来像

function calcServicesTotal() {
    var total=0;
    $('.services').each(function () {
        var id = parseInt($(this).val());
        var price = parseInt($("#srv_" + id).text());
        if (this.checked) {
            total = total + price;
            console.log("id - " + id + " price - " + price);
        }
        else {
            if (total > 0)
                total = total - price;
        }
    });
    console.log("total - " + total);
}

问题是,我可以看到console.log("id - " + id + " price - " + price);的正确值,但每次为0时total都会保持不变。我做错了什么?

这毫无意义的

else {
    if (total > 0)
        total = total - price;
}

否则根本没有意义,所以如果复选框未选中,则进行减法。因此,如果选中第一个复选框,它将使total>0,并且所有复选框都未选中,则开始减去它们的值,直到它为零。

那张支票不属于那里。