通过DOM实现试卷的检查基本信息的填写以及评分功能
- 通过对每一个文本输入框以及Radio选择框进行id的设置
- 在scrip标签中使用 document.getElementById获取节点
- 在提交的按钮上使用onclick触发事件 进而对必填信息以及答案进行判断
- 使用innerHTML方法改变节点内容,添加最后总分
- 使用.style.[样式]方法改变样式,在空白的必填信息上通过红色边框进行提醒
- 使用alert()进行提示信息,当必填信息有一项未填时显示提示信息
定义变量grade进行成绩的统计
- 使用value属性获得文本输入框的内容再使用双等号与标准答案进行判断
- 使用checked属性判断radio及checkbox是否被选中
<script>
function checkInfo() {
var classNum = document.getElementById("classNum");
var scNum = document.getElementById("scNum");
var stName = document.getElementById("stName");
if (classNum.value === "" || scNum.value === "" || stName.value === "") {
classNum.style.borderColor = "red";
scNum.style.borderColor = "red";
stName.style.borderColor = "red";
alert("请检查并填写必要信息!");
}
else {
var grade = 0;
var answer1 = document.getElementById("answer1"),
answer2 = document.getElementById("answer2"),
answer3 = document.getElementById("answer3"),
answer4 = document.getElementById("answer4"),
answer5 = document.getElementById("answer5"),
answer6 = document.getElementById("answer6"),
answer7 = document.getElementById("answer7"),
answer8 = document.getElementById("answer8"),
answer9 = document.getElementById("answer9"),
answer10 = document.getElementById("answer10"),
answer11 = document.getElementById("answer11"),
answer12 = document.getElementById("answer12"),
answer13 = document.getElementById("answer13"),
answer14 = document.getElementById("answer14"),
answer15 = document.getElementById("answer15");
if
(answer1.value == "统一建模语言") {
grade += 5;
}
if (answer2.value == "封装性") {
grade += 5;
}
if (answer3.value == "继承性") {
grade += 5;
}
if (answer4.value == "多态性") {
grade += 5;
}
if (answer5.checked) {
grade += 10;
}
if (answer6.checked) {
grade += 10;
}
if (answer7.checked && answer8.checked && answer9.checked) {
grade += 10;
}
if (answer10.checked && answer11.checked && answer12.checked) {
grade += 10;
}
if (answer13.checked) {
grade += 10;
}
if (answer14.checked) {
grade += 10;
}
if (answer15.value == "模型是对现实世界的简化和抽象,模型是对所研究的系统、过程、事物或概念的一种表达式。可以是物理实体;可以是某种图形;或者是一种数学表达式。") {
grade += 20;
}
var total = document.getElementById("totalGrade");
total.innerHTML = "得分:" + grade;
}
}
</script>
显示效果:
必填信息填写不全
必填信息填写不全
计算总分
改进:
在复选框及radio中可以使用form标签进行封装之后再获form节点 然后就可以通过数组对与每一个选项是否选中进行判断,这样一来可以使代码更加简洁。
网友评论