JavaScript 编程解决考试分数统计问题

项目实战中遇到的:

该考试题目共有25道,每一道都是2选1的选择题,总分是100分。

JavaScript代码如下:

1/**
2 * @author georgewing
3 */

4function prepareCheckBox() {
5    document.getElementById("submit").onclick = function() {
6        selectedCheckBox(4);
7    }

8 }

9function selectedCheckBox(x) {
10    var oInput = document.getElementsByTagName("input");
11    var iTotal = 0;
12    for(var i=0;i<oInput.length;i++) {
13        if(oInput[i].className == "checkedRadio") {
14            if(oInput[i].checked) {
15                //add x point
16                iTotal = iTotal + x;
17            }

18            else {
19                // add 0 point
20                iTotal = iTotal + 0;
21            }

22        }

23       
24    }

25    document.getElementById("Total").setAttribute("value", iTotal);
26    alert(iTotal);
27}

上面的代码存在不必要的DOM-2编程模型的问题,下面进行了程序的改进:

var formElms = document.forms['form'].elements;
var totalElm=formElms['Total'];
var totalNum = 0;

var selectedCheckBox = function(x){
    for(var i=0;i< formElms.length;i++) {
	if(formElms[i].type=='radio') {
            if(formElms[i].checked) {
                //add x point
                totalNum = totalNum + x;
            }
            else {
                // add 0 point
                totalNum = totalNum + 0;
            }
        }
    }
    //End for-Loop
    totalElm.value = totalNum;
    alert(totalElm.value);
};

document.forms['form'].onsubmit = function() { 
     selectedCheckBox(4);
}
posted on 2008-02-24 12:14  豆豆の爸爸  阅读(1925)  评论(0编辑  收藏  举报