这些是我的gpa计算器代码。我可以正确获取第一个模块的gpa,但是,如果我添加第二个模块,它将不再起作用。有人能帮我吗?

function calculate(){

        var credit1 = document.getElementById('credit1').value;
        var grade1 = document.getElementById('grade1').value;
        var module1 = credit1 * grade1;

        var credit2 = document.getElementById('credit2').value;
        var grade2 = document.getElementById('grade2').value;
        var module2 = credit2 * grade2;

        var credit3 = document.getElementById('credit3').value;
        var grade3 = document.getElementById('grade3').value;
        var module3 = credit3 * grade3;

        var credit4 = document.getElementById('credit4').value;
        var grade4 = document.getElementById('grade4').value;
        var module4 = credit4 * grade4;

        var credit5 = document.getElementById('credit5').value;
        var grade5 = document.getElementById('grade5').value;
        var module5 = credit5 * grade5;

        var credit6 = document.getElementById('credit6').value;
        var grade6 = document.getElementById('grade6').value;
        var module6 = credit6 * grade6;

        var tmodule = module1 + module2 + module3 + module4 + module5 + module6;
        var tcredits = credit1 + credit2 + credit3 + credit4 + credit5 + credit6;
        var gpa = (tmodule / tcredits).toFixed(2);

        document.getElementById("gpa").innerHTML = gpa;
    }

最佳答案

正如Lister先生所说,将设置更改为“ no wrap-in head”,否则您的JavaScript将无法运行。然后,您必须将值转换为数字:

var credit1 = Number(document.getElementById('credit1').value);


或这个:

var tcredits = credit1 + credit2 + credit3 + credit4 + credit5 + credit6;


将连接字符串。

编辑:
请注意,由于这些行,您不需要对成绩或模块进行此操作:

var module1 = credit1 * grade1;


运算符*适用于数字,而不适用于字符串。

10-04 10:37