Javascript字符串比较

Javascript字符串比较,javascript,html,Javascript,Html,所以,我正在尝试创建交互式测验,我几乎完成了。只有答案检查部分失败得很惨。我有问题、选项和正确答案的数组,但比较总是失败 function check(clicked_id) { document.getElementById("Question").value=" " + questionArray[i]; document.getElementById("OptionA").value=" " + aArray[i]; document.getElementById

所以,我正在尝试创建交互式测验,我几乎完成了。只有答案检查部分失败得很惨。我有问题、选项和正确答案的数组,但比较总是失败

function check(clicked_id)
{
    document.getElementById("Question").value=" " + questionArray[i];
    document.getElementById("OptionA").value=" " + aArray[i]; 
    document.getElementById("OptionB").value=" " + bArray[i]; 
    document.getElementById("OptionC").value=" " + cArray[i]; 
    document.getElementById("OptionD").value=" " + dArray[i]; 

    var selected = document.getElementById(clicked_id).value;
    var answer = answerArray[i];

    document.getElementById("text").innerHTML = answer + "<br>" + selected;

    if (selected == answer) {
        document.getElementById("comparison").innerHTML = "Correct";
    } else {
        document.getElementById("comparison").innerHTML = "Wrong";
    }   
}
功能检查(单击\u id)
{
document.getElementById(“问题”).value=”“+questionArray[i];
document.getElementById(“OptionA”).value=”“+aArray[i];
文件.getElementById(“OptionB”).value=“”+bArray[i];
document.getElementById(“OptionC”).value=”“+cArray[i];
document.getElementById(“OptionD”).value=“”+dArray[i];
选择的变量=document.getElementById(单击的id).value;
var-answer=answerArray[i];
document.getElementById(“text”).innerHTML=answer+“
”+选中; 如果(选定==回答){ document.getElementById(“比较”).innerHTML=“正确”; }否则{ document.getElementById(“比较”).innerHTML=“错误”; } }
html部分是

<input onclick="check(this.id)" type="button" value="Click here to start" id="Question" /><br><br>
<input onclick="check(this.id)" type="button" value="" id="OptionA" />
<input onclick="check(this.id)" type="button" value="" id="OptionB" />
<input onclick="check(this.id)" type="button" value="" id="OptionC" />
<input onclick="check(this.id)" type="button" value="" id="OptionD" />
<div id="text"></div>
<div id="comparison"></div>



无论出于什么原因,它都不起作用,我不明白为什么。

您似乎在值的前面添加空格,但在比较之前,您从未删除空格。至少我看不出你有没有。试试这个

var selected = document.getElementById(clicked_id).value.trim();

在比较期间,您应该修剪这两个值。像这样的

if (selected.trim() == answer.trim()) {
    document.getElementById("comparison").innerHTML = "Correct";
} else {
    document.getElementById("comparison").innerHTML = "Wrong";
} 

在哪里定义了
i
?附加一个断点,查看您选择的
应答的
变量是否具有您期望的值。没有看到更多的代码,我们只是猜测。你能把它放在一个表格中吗?如果你的测试像是为一个问题显示一个div,然后在回答后隐藏它并显示另一个div,那么如果你对每个单独div中的所有选项使用相同的id,这段代码将失败。