2013-10-28 149 views
0

我正在尋找一種方法從單選按鈕獲取我的價值。我在這裏有html。通過Jquery從電臺獲取價值

<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++; 
}); 



//  
}); 

正如你所知道的,它不斷返回undefined,我不太清楚我在做什麼錯。

順便提一句,其值是衡量這是我正在測驗中的正確答案還是不正確答案。所以,最終我需要在if語句中使用array[counter]。但是,我分開了這個測試和調整,並找出如何獲得價值。

+0

是否在頁面加載時檢查了什麼? – tymeJV

+0

我不知道該怎麼做,所以不。 –

+2

因此,在您的代碼中,您在頁面加載時提醒已檢查的單選按鈕值,但由於在加載頁面時沒有檢查到任何內容,因此您收到未定義的 – tymeJV

回答

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 
     } 
    } 
}); 

當然,你可能需要一個檢查,以確定用戶已經回答了一切,否則最終數組可能會超出界限並導致錯誤。

+0

嘿謝謝一堆。如果我在我的任何評論中聽起來都很尖銳,我很抱歉,那不是我的意圖。我一直沒有這麼做。有時,它有點令人沮喪(儘管如此)。這種方式更加優雅。 –

+0

發展就是這樣,有很多不同的方式來做事情。堅持下去,不斷提問!樂於幫助! - @ JerryWalker – tymeJV

+0

我還有一個問題......如果整個測驗只有一個數組,那麼我將如何動態添加所有答案?所顯示的唯一答案實際上是正確的答案。 –