Javascript复选框计算不正确 [英] Javascript checkboxes incorrect calculating

查看:133
本文介绍了Javascript复选框计算不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我有6个复选框,我使用他们的rel =值来相加并显示总和。但是,如果我选中框1和3和6,则添加忽略框3,不会将其添加到总和中。因此,基本上检查的最低和最高的checboxes是加起来而不是所有检查。

Hey guys i have 6 checkboxes and am using their "rel=" values to add up and display a total sum. However if I check box 1 and 3 and 6 the addition ignores box 3 and does not add it to the sum. So basically the lowest and highest checboxes checked are adding up rather than all that are checked.

想知道是否有人能找到原因。

Wondering if anyone can spot a reason why.

$(document).ready(function() {
    function recalculate() {
        var sum = 0;
        var base = 0;
        var d=new Date();
        var theDay=d.getDay();
        switch (theDay)
        {
            case 6:
              base = 30;
            break;
            case 0:
              base = 30;
              break;
            default:
            base = 49 ;
        }

        $("input[type=checkbox]:checked").each(function() {
             sum = parseInt($(this).attr("rel")) + base;
        });

        $("#output").html(sum);
    }

    $("input[type=checkbox]").change(function() {
        recalculate();
    });

});


推荐答案

$("input[type=checkbox]:checked").each(function() {
  sum = parseInt($(this).attr("rel")) + base;
});

到此:

$("input[type=checkbox]:checked").each(function() {
  sum += parseInt($(this).attr("rel")) + base;
});

使用当前代码,实际上并不计算总和,因为每次你获得 rel = 下一个复选框的值,您将覆盖之前的金额。

With your current code, the sum isn't actually being calculated, since every time you get the rel= value for the next checkbox, you're overwriting the previous sum value.

/ strong>如果你不想每次都添加基地,你可以简单地把这个分配移出循环。像这样:

If you don't want to add the base each time, you can simply move that assignment out of the loop. Like this:

sum = base;
$("input[type=checkbox]:checked").each(function() {
  sum += parseInt($(this).attr("rel"));
});

这篇关于Javascript复选框计算不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆