gpt4 book ai didi

javascript - 使用 Javascript 创建测验页面

转载 作者:行者123 更新时间:2023-11-28 07:26:49 26 4
gpt4 key购买 nike

我试图使用 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>

最佳答案

进行以下更改:

HTML

<form id = "myQuiz" onsubmit = "checkAnswers(event)" action = "">

JS

function checkAnswers(event) {
event.preventDefault();
...
}

preventDefault取消表单提交事件,该事件导致页面重新加载并且文本消失。

DEMO

关于javascript - 使用 Javascript 创建测验页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29558613/

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