项目实战中遇到的:
该考试题目共有25道,每一道都是2选1的选择题,总分是100分。
JavaScript代码如下:1
/**//**
2
* @author georgewing
3
*/
4
function prepareCheckBox()
{
5
document.getElementById("submit").onclick = function()
{
6
selectedCheckBox(4);
7
}
8
}
9
function 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
}

/**//**2
* @author georgewing3
*/4

function prepareCheckBox()
{5

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

function 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 point16
iTotal = iTotal + x;17
}18

else
{19
// add 0 point20
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);
}
本文探讨了在项目实战中遇到的JavaScript计分算法问题,原算法存在不必要的DOM操作,导致效率低下。通过优化,使用更简洁的方式遍历表单元素,实现了选择题的计分功能,提高了代码执行效率。
1358

被折叠的 条评论
为什么被折叠?



