2016-12-21 26 views
1

我有一個測驗應用程序的問題。我是新手,我的問題是,我不知道如何從JS數組提供輸入類型無線電默認值。所以當頁面加載時,你已經可以看到array [0]位置值作爲選項。JavaScript數組爲HTML無線電傳遞默認值

HTML代碼:

<p> 
<p id="question"></p> 
</p> 
    <input type="radio" name="quiz" id="ans1" > 
    <br> 
    <input type="radio" name="quiz" id="ans2"> 
    <br> 
    <input type="radio" name="quiz" id="ans3"> 
    <br> 
    <input type="radio" name="quiz" id="ans4"> 
    <br> 
<input type="submit" value="Start" onClick="RadioCheck()"> 
</form> 

JS代碼:

<script language="javascript"> 

var allQuestions = [{ 
    question: "Question1?", 
    choices: ["Answer1", "Answer2", "Answer3", "Answer4"], 
    CorrectAnswer:0}, 
    { 
    question: "Question2?", 
    choices: ["Answer1", "Answer2", "Answer3", "Answer4"], 
    CorrectAnswer:0}, 
    { 
    question: "Question3?", 
    choices: ["Answer1", "Answer2", "Answer3", "Answer4"], 
    CorrectAnswer:0}, 
    { 
    question: "Question4?", 
    choices: ["Answer1", "Answer2", "Answer3", "Answer4"], 
    CorrectAnswer:0} 
    ]; 

var currentQuestion=0; 
var CorrectAnswer=0; 


function RadioCheck() { 
//populate question in HTML 
    var question = document.getElementById("question"); 
    question.nextSibling.data = allQuestions[currentQuestion].question; 

//populate answers in HTML 
    var ans1 = document.getElementById("ans1"); 
    ans1.nextSibling.data = allQuestions[currentQuestion].choices[0]; 

    var ans2 = document.getElementById("ans2"); 
    ans2.nextSibling.data = allQuestions[currentQuestion].choices[1]; 

    var ans3 = document.getElementById("ans3"); 
    ans3.nextSibling.data = allQuestions[currentQuestion].choices[2]; 

    var ans4 = document.getElementById("ans4"); 
    ans4.nextSibling.data = allQuestions[currentQuestion].choices[3]; 

    var selection = document.getElementsByTagName('input') 

    if(selection[allQuestions[currentQuestion].CorrectAnswer].checked == true){ 
     CorrectAnswer ++; 
    } 

    currentQuestion ++; 
} 

</script> 

這工作,當我點擊開始按鈕,一日一次,但我想只要加載頁面顯示問題1和答案。

回答

0

您需要將函數添加到onload事件中。

例如,在你的身體聲明,你可以在頁面加載時的功能RadioCheck將運行填充表單中添加以下

<body onload="RadioCheck()"> 

你可以在這裏找到更多關於onload事件的信息:http://www.w3schools.com/jsref/event_onload.asp