-1

此时我只是在测试是否可以将选择的单选按钮与数组中的正确答案进行比较。请参阅下面的评论:

var allQuestions = [{
        "question": "Who was Luke's wingman in the battle at Hoth?",
        "choices": ["Dak", "Biggs", "Wedge", "fx-7"],
        "correctAnswer": 0
    }];


function answerFwd() {
    var answerOutput = " ";
    var itemAnswers = allQuestions;
    var answer = 0;
    var playerTally = 0;
    var playerFeedback = "";
    var playerMessage = document.getElementById("playerMessage");


    // Is this the correct way to store the radio button which is selected?
    var radioValue = $("input[type='radio'].radioButtons").is(':checked');

    var right = false;

    if (currentAnswer <= itemAnswers.length) {
        currentAnswer++;
    }

    createRadioButtonFromArray(itemAnswers[currentQuestion].choices);

    //Then compare value in array with radioValue value
    if(radioValue == itemAnswers.correctAnswer){
          right = true;
    }           

    if(right) {
        alert("You answered correctly");
    } else {
        alert("Wrong answer");
    }

}

我怀疑我的错误是我没有correctAnswer:3radioValue正确的比较。有意义的是按钮的索引与值匹配。会for-loop是最好的方法吗?提前致谢!

更新

这是创建按钮的代码:

 function createRadioButtonFromArray(array) {
   var len = array.length; 
   var responses = document.getElementById("responses"); 
   responses.innerHTML = ''; 
    for (var i = 0; i < len; i++) {
     radio = document.createElement("input"); 
     radio.type = "radio";
     radio.name = "choices"; 
     radio.className = "radioButtons"; 
     radio.value = i; 
     radio.id = "choice" + i; 
     var radioText = document.createElement("div"); 
     radioText.id = "c" + i; 
     radioText.className = "choiceText"; 
     radioText.innerHTML = array[i]; 
     responses.appendChild(radio); 
     responses.appendChild(radioText); 
   }
}

这就是它的呈现方式:

<div id="responses">
<input type="radio" name="choices" class="radioButtons" value="0" id="choice0">
<div id="c0" class="choiceText">The Avenger</div>
<input type="radio" name="choices" class="radioButtons" value="1" id="choice1">
<div id="c1" class="choiceText">Devastator </div>
<input type="radio" name="choices" class="radioButtons" value="2" id="choice2">
<div id="c2" class="choiceText">Conquest</div>
<input type="radio" name="choices" class="radioButtons" value="3" id="choice3">
<div id="c3" class="choiceText">The Executor</div>

4

1 回答 1

0

这是存储所选单选按钮的正确方法吗?

var radioValue = $("input[type='radio'].radioButtons").is(':checked');

不,那将是:

var radioValue = $("input[type='radio'].radioButtons:checked").val();

更多的

于 2015-04-04T21:44:17.230 回答