我试图使用Javascript创建一个简单的测验页面。此外它进展顺利,但在浏览器中运行此代码后,按下提交按钮,段落中出现的DOM文本(通过脚本)在闪光后消失。我曾预计文字会一直显示在屏幕上,直到下一个动作。请帮我解决这个问题。
谢谢
代码
<!DOCTYPE HTML>
<html>
<head>
<title>
Quiz
</title>
<script type = "text/Javascript">
function checkAnswers()
{
var myQuiz = document.getElementById( "myQuiz" );
if ( myQuiz.elements[ 2 ].checked )
document.getElementById("demo").innerHTML = "Congrats, Thats the Right answer";
else
document.getElementById("demo").innerHTML = "Woops!! The Correct answer is 'Mouse'.<br>Click 'Next' to Proceed";
}
</script>
</head>
<body>
<br><br><br><br><br><br>
<form id = "myQuiz" onsubmit = "checkAnswers()" action = "">
Which among the following is readily found in computers ?
<br><br><br>
<input type = "radio" name = "radiobutton" value = "A" /><label> Zebra</label>
<input type = "radio" name = "radiobutton" value = "B" /><label> Girrafe</label>
<br><br> <input type = "radio" name = "radiobutton" value = "C" /><label>Mouse</label>
<input type = "radio" name = "radiobutton" value = "D" /><label>Mosquito</label>
</div><br><input type = "submit" name = "submit" value = "Submit" />
<br>
<p id = "demo" "> </p>
</form>
</body>
</html>
答案 0 :(得分:0)
进行以下更改:
HTML
<form id = "myQuiz" onsubmit = "checkAnswers(event)" action = "">
JS
function checkAnswers(event) {
event.preventDefault();
...
}
preventDefault
取消了表单提交事件,导致页面重新加载,文本消失。
答案 1 :(得分:0)
只需返回&#34; false&#34;在onSubmit参数中,如下所示:
<form id = "myQuiz" onsubmit = "return false" action = "">
当有人点击按钮时调用checkAnswers()
功能;
<input type = "submit" name = "submit" value = "Submit" onclick="checkAnswers()" />