項目實戰中遇到的:
該考試題目共有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);}