猿问

使正确答案为绿色,错误答案为红色用于JS测验

我有一个在JS中创建的测验系统。我正在使用输入元素来显示每个测验选项。我试图使它,所以当你点击提交时,它将循环遍历每个输入元素,如果输入文本是正确的答案,则将输入文本的样式设置为绿色,如果它是一个不正确的答案,则设置为红色。但是,我实际上很难获得输入值旁边的文本。


下面是测验的图片:https://gyazo.com/1ba5245de2c5c6f96bd728e31aeb0899


网页:


<!DOCTYPE html>

<html>

<head>


<link href ="style.css" rel ="stylesheet">

<!-- <link href="https://fonts.googleapis.com/css?family=OpenSans" rel="stylesheet"> -->

<script src = "main.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>



<body>

<h1>Chapter 1 Quiz</h1>



<form id = "quiz" name = "quiz">

<p class = "questions">What is the capital of Rhode Island?</p>

<input id = "textbox" type = "text" name = "question1">


<p class = "questions">What is the capital of Connecticut?</p>

<input type = "radio" id = "mc" name = "question2" value = "Hartford"> Hartford<br>



<input type = "radio" id = "mc" name = "question2" value = "Heartford"> Heartford<br>


<p class = "questions">What is the capital of New York?</p>

<input type = "radio" id = "mc" name = "question3" value = "Albany"> Albany<br>

<input type = "radio" id = "mc" name = "question3" value = "All Benny's"> All Benny's<br>



<input id = "button" type = "button" value = "Finish" onclick = "check();">

</form>


<div id = "after_submit">

<p id = "number_correct"></p>

<p id = "message"></p>

</div>

</html>


</body>


慕容708150
浏览 136回答 3
3回答

SMILET

为什么简单不要使用类:如果 (ans == 正确) { $(这个).切换类(正确 ); } 如果 (ans != 正确) { $(这个).切换类(错误); }你需要在css上使用的文本颜色

不负相思意

这是通过添加一个其他条件来完成的风格.mystyle{&nbsp; &nbsp; border-color: red;}if (question2 == "Hartford") {&nbsp; &nbsp; correct++;}&nbsp; &nbsp;else{var element = document.getElementById("textbox");&nbsp;element.classList.add("mystyle");}检查我的小提琴在这里点击

吃鸡游戏

此代码不好。我决定在一个地方用正确的答案重写它。此外,我为每个输入元素添加了标签,以便我可以更好地操作CSS。下面是 JS:function check(){&nbsp; &nbsp; var correct = 0;&nbsp; &nbsp; var total_questions = 3;&nbsp; &nbsp; var correct_answers = ["Providence", "Hartford", "Albany"];&nbsp; &nbsp; $( "label" ).each(function( index ) {&nbsp; &nbsp; &nbsp; &nbsp; console.log( index + ": " + $( this ).text() );&nbsp; &nbsp; &nbsp; &nbsp; if (correct_answers.includes($( this ).text())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.style.color = 'green'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; correct++&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.style.color = 'red'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; document.getElementById("after_submit").style.visibility = "visible";&nbsp; &nbsp; document.getElementById("message").innerHTML = "Correct Answers:";&nbsp; &nbsp; document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答