[英]I'm trying to create a quiz with JavaScript and I can't get my button to work
I can't get my head around JavaScript at all, I'm trying to create a quiz but every way I go about it, I can't seem to get the form to submit. 我根本无法理解JavaScript,我正在尝试创建一个测验,但是无论如何,我似乎都无法提交表单。 This is just the section of the code from my HTML website.
这只是我的HTML网站中的代码部分。
<b>Quiz</b>
<br><br>
<center><p>Q 1) What colour is this laptop?</p>
<table width="200">
<tr>
<td><input type="radio" name="radio" id="a1" value="a1" />
Orange</td>
<td><input type="radio" name="radio" id="a2" value="a1" />
White</td>
</tr>
<tr>
<td><input type="radio" name="radio" id="a3" value="a1" />
Blue</td>
<td><input type="radio" name="radio" id="a4" value="a1" />
Red</td>
</tr>
</table>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit"
onClick="fSubmit()" /></center>
</p>
<script type="text/javascript">
function fSubmit(){
var correctanswer = document.getElementById("a3")
if (correctanswer.checked *** true) {
alert("Correct!")
}
else {
alert("Incorrect!")
}
}
</script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<b>Quiz</b>
<br><br>
<form>
<center>
<p>Q 1) What colour is this laptop?</p>
<table width="200">
<tr>
<td>
<input type="radio" name="radio" id="a1" value="a1" />
Orange
</td>
<td>
<input type="radio" name="radio" id="a2" value="a1" />
White
</td>
</tr>
<tr>
<td>
<input type="radio" name="radio" id="a3" value="a1" />
Blue
</td>
<td>
<input type="radio" name="radio" id="a4" value="a1" />
Red
</td>
</tr>
</table>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit"
onclick="fSubmit()" />
</center>
</form>
</p>
<script type="text/javascript">
function fSubmit() {
var correctanswer = document.getElementById("a3")
if (correctanswer.checked === true) {
alert("Correct!")
}
else {
alert("Incorrect!")
}
}
</script>
</body>
</html>
Add the form tag. 添加表单标签。 It will work in some browsers without form tag.
它将在某些没有表单标签的浏览器中运行。 It is a good practice to place a form tag.
放置表单标签是一个好习惯。 Also in if, replace *** with ===
同样在if中,将***替换为===
If there is a JavaScript error (such as the *** instead of === in your code example), the click event will not fire. 如果出现JavaScript错误(例如代码示例中的***而不是===),则不会触发click事件。 You can open up the JavaScript debugger (sometimes called console) in your browser to see any errors.
您可以在浏览器中打开JavaScript调试器(有时称为控制台)以查看任何错误。
Also, it seems as though you do not want to "submit" your button click to the server, so the input type should be button (not submit) or else use the on submit event on the form instead of the onclick event on the button. 另外,似乎您不想将按钮单击“提交”到服务器,因此输入类型应为按钮(而不是提交),否则请使用表单上的on Submit事件而不是按钮上的onclick事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.