为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容708150 2022-09-11 20:28:43
我有一个在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>
查看完整描述

3 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

为什么简单不要使用类:

如果 (ans == 正确) { $(这个).切换类(正确 ); } 如果 (ans != 正确) { $(这个).切换类(错误); }

你需要在css上使用的文本颜色


查看完整回答
反对 回复 2022-09-11
?
不负相思意

TA贡献1777条经验 获得超10个赞

这是通过添加一个其他条件来完成的


风格


.mystyle{

    border-color: red;

}



if (question2 == "Hartford") {

    correct++;

}   

else{

var element = document.getElementById("textbox");

 element.classList.add("mystyle");

}

检查我的小提琴在这里点击


查看完整回答
反对 回复 2022-09-11
?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

此代码不好。我决定在一个地方用正确的答案重写它。此外,我为每个输入元素添加了标签,以便我可以更好地操作CSS。


下面是 JS:



function check(){


    var correct = 0;

    var total_questions = 3;

    var correct_answers = ["Providence", "Hartford", "Albany"];


    $( "label" ).each(function( index ) {

        console.log( index + ": " + $( this ).text() );

        if (correct_answers.includes($( this ).text())) {

            this.style.color = 'green'

            correct++

        } else {

            this.style.color = 'red'


        }

    });


    document.getElementById("after_submit").style.visibility = "visible";


    document.getElementById("message").innerHTML = "Correct Answers:";

    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";



    }


查看完整回答
反对 回复 2022-09-11
  • 3 回答
  • 0 关注
  • 135 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号