0

我正在编写一个 JS 代码来计算给定一些个人成绩的最终成绩并在 html 页面中输出结果,但是当我触发事件和函数时,它会在一瞬间输出错误答案,然后立即与输入的值一起消失文本框。

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Problem 2</title>
        <script src="grades.js" type="text/javascript"></script>
    </head>

    <body>
        <h1>Grade Calculator</h1>
        <form id ="myForm">
            <div id="assignments">
            HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
            HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
            HW <input type="text" size="1"/> / <input type="text" size="1"/>
            </div>

            <div>
                <input type="checkbox" /> Curve +5?
            </div>

            <div id="resultsarea">
                <p>
                    <!--add buttons here -->
                    <button id="comp">Compute</button>
                    <button id="clr">Clear</button>
                </p>

                <!-- add results here -->
            </div>
        </form>
    </body>
</html>

JS:

window.onload = pageLoad;

function pageLoad()
{
    var cbutton = document.getElementById("comp");
    cbutton.onclick = compute;
}

function compute()
{
    var values = document.getElementsByTagName("input");
    var marks = 0;
    var total = 0;
    for (var i=0; i < values.length; i++)
    {
        if(values[i].type == "text")
        {
            if (i%2 == 0)
            marks += parseInt(values[i].value);
            else
            total += parseInt(values[i].value);
        }
    }
    var result = Math.round(marks/total);
    document.writeln(result);
}
4

0 回答 0