gpt4 book ai didi

javascript - 我的 javascript 测验在提交后未显示结果

转载 作者:行者123 更新时间:2023-12-02 21:08:06 25 4
gpt4 key购买 nike

我正在玩 javascript 测验,但在显示结果时遇到问题。我希望用户在单击“提交答案”但没有任何反应时看到正确的结果。

这是我的 HTML 代码:

<!DOCTYPE html>
<html>
<head>
<title> Simple JavaScript Quiz </title>
<link rel="stylesheet" href="css/style.css">

<script src="js/script.js"> </script>
</head>
<body>
<div id="container">
<header>
<h1> Simple JavaScript Quiz</h1>
<p> Test your knowledge in <strong>JavaScript fundamentals</strong></p>
</header>
<section>
<div id="results"> </div>

<form name="quizForm" onsubmit="return submitAnswers()">

<h3>1. In which elements do we put in JavaScript code?</h3>
<img src="scam.png" alt="Italian Trulli">
<input type="radio" name="q1" value="a" id="q1a">a. &lt;js&gt;<br>
<input type="radio" name="q1" value="b" id="q1b">b. &lt;script&gt;<br>
<input type="radio" name="q1" value="c" id="q1c">c. &lt;body&gt;<br>
<input type="radio" name="q1" value="d" id="q1d">d. &lt;link&gt;<br>

<h3>2. Which HTML attribute is used to reference an external JavaScript file?</h3>
<input type="radio" name="q2" value="a" id="q2a">a. src<br>
<input type="radio" name="q2" value="b" id="q2b">b. rel<br>
<input type="radio" name="q2" value="c" id="q2c">c. type<br>
<input type="radio" name="q2" value="d" id="q2d">d. href<br>

<h3>3. How would you write "Hello" in an alert box?</h3>
<input type="radio" name="q3" value="a" id="q3a">a. msg("Hello");<br>
<input type="radio" name="q3" value="b" id="q3b">b. alertBox("Hello");<br>
<input type="radio" name="q3" value="c" id="q3c">c. document.write("Hello");<br>
<input type="radio" name="q3" value="d" id="q3d">d. alert("Hello");<br>

<input type="submit" value="Submit Answers"> <br><br>

</form>
</section>

</div>
</body>
</html>

这是我的 JavaScript 代码:

function submitAnswers() {

var total = 3;
var score = 0;

// get user input

var q1 = document.forms["quizForm"]["q1"].value;
var q2 = document.forms["quizForm"]["q2"].value;
var q3 = document.forms["quizForm"]["q3"].value;

// set correct answers

var answers = ['b', 'a', 'd'];

// check answers (note i - 1 to account for array starting with [0])

for (var i = 1; i <= total; i++) {
if (eval("q" + i) == answers[i - 1]) {
score++;
}
}

// display results

var results = document.getElementById("results");
results.innerHTML ='<h3>You Scored <span> '+score+' </span> out of <span>'+total+'</span> </h3>';
alert('You Scored '+score+' out of '+total);
}

点击“提交答案”后,没有任何反应。有什么想法吗?

最佳答案

不要直接在表单元素中添加 onsubmit 属性,而是在其上添加 submit 事件监听器并阻止该事件的默认行为。提交表单的默认行为是刷新整个页面。

document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
submitAnswers();
})

关于javascript - 我的 javascript 测验在提交后未显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61171912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com