2014-02-11 26 views
-1

我将使用JavaScript来创建和评分测验。它有20个问题,并随机挑选其中10个作为测验。我需要帮助的是在下面的真实长行中找到。看看它说id =“q +正确”?此ID将用于对测验进行评分以查看是否进行了检查。变量“q”包含为测验随机选择的数字(从1到10)。例如:如果q = 1(它在测验中首先被选中),我将使用document.getElementById('1correct').checked来查看它是否被选中。但是,我不知道如何在此上下文中将变量“q”连接到字符串“correct”。我会很感激任何答案。如何将字符串添加到<input>标记中的变量?

function choosequestions(){ 
    var qList = []; 
    for(q=1; q < 11; q++){ 
     var question = Math.floor((Math.random()*20)+1); 
     while (qList.indexOf(question) !== -1) { 
      question = Math.floor((Math.random()*20)+1); 
     } 
     qList.push(question); 

     if (question==1){ 
      document.getElementById(q).innerHTML='Question '+ q +'. Which of these freedoms are protected in the 1st amendment?<br /><br /><input id="q + correct" type="radio" name="fav" value="country" />Freedoms of Religion, Speech and Petition.<br /> <input id="q + .2" type="radio" name="fav" value="blues" />Right to bear arms.<br /> <input id="q + .3" type="radio" name="fav" value="rock" />Right to \"Life, liberty, and the pursuit of happiness.\"<br /> <input id="q + .4" type="radio" name="fav" value="pop" />All of the above.</form>' 
     } 
    } 
} 

回答

0

在JavaScript中,单撇号''和双引号""都用于字符串,但可以单独使用。

正如你添加的第一个q变量到HTML与:

document.getElementById(q).innerHTML = 'Question ' + q + '... rest of string'; 

您需要打破字符串添加变量q,并早在添加字符串的其余这将需要要在innerHTML字符串的多个部分完成,而不仅仅是在'correct'发生的位置。

下面是你应该插入的文本更简洁的外观:

document.getElementById(q).innerHTML = 'Question '+ q + 
    '. Which of these freedoms are protected in the 1st amendment?<br /><br />' + 
    '<input id="' + q + 'correct" type="radio" name="fav" value="country" />Freedoms of Religion, Speech and Petition.<br />' + 
    '<input id="' + q + '.2" type="radio" name="fav" value="blues" />Right to bear arms.<br />' + 
    '<input id="' + q + '.3" type="radio" name="fav" value="rock" />Right to \"Life, liberty, and the pursuit of happiness.\"<br />' + 
    '<input id="' + q + '.4" type="radio" name="fav" value="pop" />All of the above.</form>'; 

注意,你必须做同样的事情与id对投入'correct''.2''.3''.4'

+0

我有点麻烦,我的功能,检查哪个无线电框被选中。你能帮助@TyrannicalTyrannosaurus吗? JS可以在这里找到:http://js.do/ianhazzard/31112 –

+0

太棒了! Fo sho - 它看起来像在第二个输入(第8行)中错过了'onClick'的一个'''标记:D –

1

因为长串封装有省略号,你应该能够做到这一点是这样的:

'<input id="' + q + 'correct" type="radio" name="fav" value="country" />' 
相关问题