试图在我的网络开发课程中实际运用我正在学习的技能,我正在尝试为我的合作伙伴的小学课程创建一个关于维京人的网站。
我已经设法获得了我想要的HTML和CSS,但我在使用Javascript时遇到了一些困难。这一切看起来都很好,但不会按预期运行。
我有一个测验和一个提交按钮。单击此按钮将在我的.js文件中引用“checkresults”功能。
然后应该计算0到3之间的结果并将此结果发布到HTML页面中。我已经设计了结果显示的框,以便在单击“提交”按钮之前不可见。但是,当运行时,结果框只会在消失之前出现一秒钟,我无法弄清楚原因。
非常感谢任何帮助或建议!
// // JAVASCRIPT
function checkresults() {
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var correct = 0;
if (question1 == "793") {
correct++;
}
if (question2 == "Shield") {
correct++;
}
if (question3 == "1066") {
correct++;
}
var message = ["You're a real Viking!", "Not bad but you can do better!",
"Odin would not be pleased with your effort!"];
var range;
if (correct < 1) {
range = 2;
}
if (correct > 0 && correct < 3) {
range = 1;
}
if (correct > 2) {
range = 0;
}
document.getElementById("afterSubmit").style.visibility = "visible"
document.getElementById("message").innerHTML = message[ramge];
document.getElementById("correct").innerHTML = "You got " + correct + "
correct!";
}
//HTML//
<form id="quiz" name="quiz">
<p>When did the Vikings first invade Britain?</p>
<input type="radio" id="mc" name="question1" value="1066" />1066<br />
<input type="radio" id="mc" name="question1" value="793" />793<br />
<input type="radio" id="mc" name="question1" value="411" />411<br />
<input type="radio" id="mc" name="question1" value="1999" />1999<br />
<p>what did every man need before he was allowed to go Viking?</p>
<input type="radio" id="mc" name="question2" value="Shield" />Shield<br />
<input type="radio" id="mc"name="question2" value="Sword" />Sword<br />
<input type="radio" id="mc"name="question2" value="Cloak" />Cloak<br />
<input type="radio" id="mc" name-"question2" value="Gold" />Gold<br />
<p>when did the Viking age end?</p>
<input type="radio" id="mc" name="question3" value="793" />793<br />
<input type="radio" id="mc" name="question3" value="1999" />1999<br />
<input type="radio" id="mc" name="question3" value="1066" />1066<br />
<input type="radio" id="mc" name="question3" value="1500" />1500<br />
<input type="submit" id="button" value="Lets see how you did!" onclick =
"checkresults();">
</form>
<div id="afterSubmit">
<p id="message"></p>
<p id="correct"></p>
//CSS//
#afterSubmit {
visibility: hidden;
border-color: red;
border-style: solid;
border-width: 5px;
}
答案 0 :(得分:2)
您的页面令人耳目一新。
更改此方法的最佳方法是将函数移动到onsubmit事件表单。
//Remove the onclick
<input type="submit" id="button" value="Lets see how you did!" onclick="checkresults();">
添加函数并将false返回到表单上的事件,因此取消提交
//Add the onsubmit, notice the return false, so it cancels submission
<form id="quiz" name="quiz" onsubmit="checkresults();return false;">