0

我正在寻找一种从单选按钮中获取价值的方法。我这里有html。

<div id="main_">
    <div class="facts_div">
        <span class="question"></span>
        <ul></ul>
    </div>
    <div id = "next_button">
    <form>
        <input id="x" type="button" class="myBtn" value="Press Me">
    </form>
    </div>
</div>
</div>

这是Jquery代码。

$(document).ready (function () {

//

var answers = 
[["Fee","Fi","Fo"], 
["La","Dee","Da"]],
questions = 
["Fee-ing?",
"La-ing?"],
corAns = ["Fee", "La"];

var counter = 0;
var correctAnswers = 0;

var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');


$btn.on('click', function() {
    if (counter < questions.length) {
        $question.text(questions[counter]);

        var ansstring = $.map(answers[counter], function(value) {
            return '<li><input type="radio" name="ans" value="0"/>'
            + value + '</li>'}).join('');
        $ul.html(ansstring);
        alert($('input[name="ans"]:checked').val())
        //if ($('input[name=ans]:checked').val() == corAns[counter]) {
            //correctAnswers++;
        //}
    }
    else {
        $facts.text('You are done with the quiz ' + correctAnswers);
        $(this).hide()
    }
    counter++;
});



//    
});

如您所知,它一直返回未定义,我不太确定我做错了什么。

顺便说一句,价值在于衡量这是我正在做的测验中的正确答案还是错误答案。所以,最终我需要array[counter]在 if 语句中使用。但是,我把它拆开来测试和调整并弄清楚如何获得价值。

4

1 回答 1

0

我相信你让这比需要的复杂得多。您只需要一组正确答案,然后单击按钮即可循环并检查答案(您将在评论中看到逐个播放):

$btn.on('click', function() {
    //Your answers array should never be longer than your questions length, so that check is a bit useless, scrap it
    //Lets first gather all your answers into an array, the .map function is built for this:

    var currentAnswers = $('input[name="ans"]:checked').map(function() {
        return this.value;
    }).get();

    //Now that we have all the checked radio buttons from the quiz, loop and compare to your answers array, if they match, do something
    //You have a 2D array of answers, then one of correct answers, you only need 1 array, and that should contain the correct responses, so eliminate the 2D array
    //Your correct answers should be: corAns = ["Fee", "La"];

    var correct = 0; //current number of correct answers
    for (var i = 0; i < currentAnswers.length; i++) {
        if (currentAnswers[i] == corAns[i]) {
            correct++; //Increment correct variable
        }
    }
});

当然,您可能需要检查以确保用户已回答所有问题,否则最终数组可能会超出范围并导致错误。

于 2013-10-29T00:27:29.950 回答