将两个不同数组的结果值相加 [英] Adding result values from two different arrays together

查看:149
本文介绍了将两个不同数组的结果值相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看我的示例 小提琴

Please take a look at my sample Fiddle

我为转帐"选择的学分有一个总计.当您选择学分数量时,累计总和.它的设计目的是每节6个学分.这部分工作正常.

I have a running total for credits selected for Transfer. As you select the number of credits, the running total adds up. It's designed to stop at 6 credits per section. This part works fine.

我想做的是将两个不同的结果集加在一起...

What I'm trying to do is add two different result sets together...

通讯 + 人文科学 = 总学分

...,并将其显示在总积分:字段中.这就是我迷路的地方.

...and have it display in the Total Credits: field. This is where I'm getting lost.

我不知道如何将两个不同的字段加在一起...

这就是我用来获得最终结果的原因( 72是这样,所以计数将以最大72个传输学分停止)

This is what I'm using to get that final result... (the 72 is so that the count will stop at 72 transfer credits maximum)

JavaScript ...

$(function($) {
    $('#total_Credits select').change(function() {
        var sum = 0;
        $('#total_Credits select').each(function(idx, elm) {
            sum += parseFloat(elm.value, 10);
        });

     $('#total_Credits').html(Math.min(sum,72).toFixed(2))
    });
});

HTML ...

Total Credits: &nbsp;&nbsp;<span id="total_Credits" style="color: red; font-weight:bold; font-size: 2em;"></span>  

推荐答案

每组选择都不需要不同的功能.相反,您可以只使用

You don't need a different function for each group of selects. Instead, you can just use

$(function($) {
    var sum = function($els, prop) {
        var s = 0;
        $els.each(function(idx, elm) {
            s += parseFloat(elm[prop], 10) || 0;
        });
        return s;
    };
    $('.select-wrapper select').change(function() {
        var $wrap = $(this).closest('.select-wrapper');
        $wrap.find('.sum').html(Math.min(sum($wrap.find('select'), 'value'),6).toFixed(2));
        $('.total-sum').html(Math.min(sum($('.sum'), 'innerHTML'),72).toFixed(2));
    });
});

演示

请注意,为了使它正常工作,我对html进行了一些修改,并且修复了类似的问题,例如重复的id s和无意义的<br>.

Note I have modified a bit the html in order to make it work, and I have fixed problems like duplicate ids and nonsense <br>.

这篇关于将两个不同数组的结果值相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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