用js写一个在线考试系统
时间: 2024-04-30 12:18:50 浏览: 81
好的,下面是一个简单的在线考试系统的代码示例:
HTML部分:
```
<!DOCTYPE html>
<html>
<head>
<title>在线考试系统</title>
</head>
<body>
<h1>在线考试系统</h1>
<div id="quiz">
<h2 id="question"></h2>
<ul>
<li><input type="radio" name="choice" value="A" id="choiceA"><label for="choiceA" id="labelA"></label></li>
<li><input type="radio" name="choice" value="B" id="choiceB"><label for="choiceB" id="labelB"></label></li>
<li><input type="radio" name="choice" value="C" id="choiceC"><label for="choiceC" id="labelC"></label></li>
<li><input type="radio" name="choice" value="D" id="choiceD"><label for="choiceD" id="labelD"></label></li>
</ul>
<button id="submit">提交</button>
<p id="result"></p>
</div>
<script src="quiz.js"></script>
</body>
</html>
```
JavaScript部分:
```
var questions = [
{
question: "什么是JS?",
choices: ["Java", "JavaScript", "JSP", "JQuery"],
correctAnswer: 1
},
{
question: "CSS是用来做什么的?",
choices: ["控制HTML的样式", "控制HTML的行为", "控制HTML的结构", "控制HTML的内容"],
correctAnswer: 0
},
{
question: "HTML5中新增了哪个标签?",
choices: ["<header>", "<section>", "<footer>", "以上都是"],
correctAnswer: 3
},
{
question: "以下哪个不是JS框架?",
choices: ["React", "Angular", "Vue", "Bootstrap"],
correctAnswer: 3
}
];
var currentQuestion = 0;
var score = 0;
var totalQuestions = questions.length;
var quizContainer = document.getElementById("quiz");
var questionElement = document.getElementById("question");
var choiceElements = document.getElementsByTagName("label");
var choiceA = document.getElementById("labelA");
var choiceB = document.getElementById("labelB");
var choiceC = document.getElementById("labelC");
var choiceD = document.getElementById("labelD");
var submitButton = document.getElementById("submit");
var resultElement = document.getElementById("result");
function loadQuestion() {
var q = questions[currentQuestion];
questionElement.textContent = (currentQuestion + 1) + ". " + q.question;
choiceA.textContent = q.choices[0];
choiceB.textContent = q.choices[1];
choiceC.textContent = q.choices[2];
choiceD.textContent = q.choices[3];
}
function getSelected() {
var choices = document.getElementsByName("choice");
for (var i = 0; i < choices.length; i++) {
if (choices[i].checked) {
return choices[i].value;
}
}
return -1;
}
function checkAnswer() {
var answer = getSelected();
if (answer == -1) {
alert("请选择一个答案!");
return;
}
if (answer == questions[currentQuestion].correctAnswer) {
score++;
}
currentQuestion++;
if (currentQuestion == totalQuestions) {
submitButton.textContent = "完成";
}
if (currentQuestion == totalQuestions + 1) {
quizContainer.style.display = "none";
resultElement.textContent = "你的得分是 " + score + " 分,共 " + totalQuestions + " 道题。";
return;
}
loadQuestion();
}
loadQuestion();
submitButton.addEventListener("click", checkAnswer);
```
这是一个比较简单的示例,你可以根据需要进行修改和完善。
阅读全文