Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使至少一个单选按钮必须被选中,如果它';不是,唐';不允许用户转到下一个问题?_Javascript - Fatal编程技术网

Javascript 如何使至少一个单选按钮必须被选中,如果它';不是,唐';不允许用户转到下一个问题?

Javascript 如何使至少一个单选按钮必须被选中,如果它';不是,唐';不允许用户转到下一个问题?,javascript,Javascript,我的测验有问题。它是直接在JS中生成的,我不知道如何使它工作 我尝试了一些JS函数,但没有一个对我有效 var quiz = [{ "question": "otazka1", "choices": ["nespravne1", "nespravne2", "spravne", "nespravne3"], "correct": "spravne" }, { "question": "otazka2", "choices": ["spravne", "nespravne1"

我的测验有问题。它是直接在JS中生成的,我不知道如何使它工作

我尝试了一些JS函数,但没有一个对我有效

var quiz = [{
  "question": "otazka1",
  "choices": ["nespravne1", "nespravne2", "spravne", "nespravne3"],
  "correct": "spravne"
 }, {
  "question": "otazka2",
  "choices": ["spravne", "nespravne1", "nespravne2", "nespravne3"],
  "correct": "spravne"
 }, {
  "question": "otazka3",
  "choices": ["nespravne1", "nespravne2", "spravne", "nespravne3"],
  "correct": "spravne"
 }, {
  "question": "otazka4",
  "choices": ["nespravne1", "nespravne2", "spravne", "nespravne3"],
  "correct": "spravne"
 }, {
  "question": "otazka5",
  "choices": ["nespravne1", "spravne", "nespravne2", "nespravne3"],
  "correct": "spravne"
 }, {
  "question": "otazka6",
  "choices": ["nespravne1", "nespravne2", "nespravne3", "spravne"],
  "correct": "spravne"
 }];

var content = $("content"),
questionContainer = $("question"),
choicesContainer = $("choices"),
scoreContainer = $("score"),
submitBtn = $("submit");

 // init vars
var cQarr = [];
for (var i=0; i<quiz.length; i++) { cQarr[i] = i; } // create sequence 
and
for (var i=0; i<cQarr.length; i++) {                // scramble order
  var rnd = Math.floor(Math.random()*cQarr.length);
  var tmp = cQarr[rnd];  cQarr[rnd] = cQarr[i]; cQarr[i] = tmp;
}
var currentQuestion = 0,
score = 0,
askingQuestion = true;

function $(id) { // shortcut for document.getElementById
return document.getElementById(id);
}

function askQuestion() {
 var choices = quiz[cQarr[currentQuestion]].choices,
  choicesHtml = "";

 // loop through choices, and create radio buttons
 for (var i = 0; i < choices.length; i++) {
 choicesHtml += "<input type='radio' name='quiz" + currentQuestion +
   "' id='choice" + (i + 1) +
   "' value='" + choices[i] + "'>" +
   " <label for='choice" + (i + 1) + "'>" + choices[i] + "</label><br>";
  }

  // load the question
  questionContainer.textContent = "Otazka " + (currentQuestion + 1) + ". 
  " +
   quiz[cQarr[currentQuestion]].question;

  // load the choices
  choicesContainer.innerHTML = choicesHtml;

  // setup for the first time
  if (currentQuestion === 0) {
    scoreContainer.textContent = "Skore: 0 spravnych  " +
      quiz.length + " z moznych.";
    submitBtn.textContent = "Potvrdit odpoved";
  }
  }

 function checkAnswer() {
  // are we asking a question, or proceeding to next question?
  if (askingQuestion) {
  submitBtn.textContent = "Dalsia otazka";
   askingQuestion = false;

  // determine which radio button they clicked
  var userpick,
  correctIndex,
  radios = document.getElementsByName("quiz" + currentQuestion);
  for (var i = 0; i < radios.length; i++) {
  if (radios[i].checked) { // if this radio button is checked
  userpick = radios[i].value;
  }

  // get index of correct answer
  if (radios[i].value == quiz[cQarr[currentQuestion]].correct) {
   correctIndex = i;
  }
   }  

  // setup if they got it right, or wrong
  var labelStyle = document.getElementsByTagName("label") 
  [correctIndex].style;
  labelStyle.fontWeight = "bold";
  if (userpick == quiz[cQarr[currentQuestion]].correct) {
    score++;
    labelStyle.color = "green";
  } else {
    labelStyle.color = "red";
   }

  scoreContainer.textContent = "Skore: " + score + " spravna odpoved " +
   quiz.length + " z moznych.";
    } else { // move to next question
     // setting up so user can ask a question
    askingQuestion = true;
     // change button text back to "Submit Answer"
      submitBtn.textContent = "Potvrdit odpoved";
      // if we're not on last question, increase question number
      if (currentQuestion < quiz.length - 1) {
     currentQuestion++;
     askQuestion();
    } else {
     showFinalResults();
  }
 }
}
var测验=[{
“问题”:“otazka1”,
“选择”:[“nespravne1”、“nespravne2”、“spravne”、“nespravne3”],
“正确”:“spravne”
}, {
“问题”:“otazka2”,
“选择”:[“spravne”、“nespravne1”、“nespravne2”、“nespravne3”],
“正确”:“spravne”
}, {
“问题”:“otazka3”,
“选择”:[“nespravne1”、“nespravne2”、“spravne”、“nespravne3”],
“正确”:“spravne”
}, {
“问题”:“otazka4”,
“选择”:[“nespravne1”、“nespravne2”、“spravne”、“nespravne3”],
“正确”:“spravne”
}, {
“问题”:“otazka5”,
“选择”:[“nespravne1”、“spravne”、“nespravne2”、“nespravne3”],
“正确”:“spravne”
}, {
“问题”:“otazka6”,
“选择”:[“nespravne1”、“nespravne2”、“nespravne3”、“spravne”],
“正确”:“spravne”
}];
变量内容=$(“内容”),
questionContainer=$(“问题”),
choicesContainer=$(“选项”),
scoreContainer=$(“分数”),
submitBtn=$(“提交”);
//初始化变量
var cQarr=[];

对于(var i=0;i如果未选择任何问题,只需相应地添加处理程序或警报

$(document).ready(function(){
  "use strict";

  var questions = [{
    question: "What is defined in physics as 'a nuclear reaction in which nuclei combine to form more massive nuclei'?",
    choices: ['fission', 'fusion', 'farking', 'fracking', 'freaking'],
    correctAnswer: 1
  }, {
    question: "What is the capital of Australia?",
    choices: ["Melbourne", "Sydney", "Canberra", "Queensland", "Christchurch"],
    correctAnswer: 2
  }, {
    question: "Who is the prime minister of the U.K.?",
    choices: ['Tony Blair', 'David Cameron', 'Nicolas Sarkozy', 'Gordon Brown', 'Sir John Major'],
    correctAnswer: 1
  }, {
    question: "What is the first perfect number?",
    choices: [38, 6, 0, 256, 28],
    correctAnswer: 1
  }, {
    question: "What colors are on the flag of Norway?",
    choices: ["red and blue", "red and white", "red, white, and silver", "red, white, and blue", "blue and gold"],
    correctAnswer: 3
  }, {
    question: "When did the Soviet Union collapse?",
    choices: ["14 February 1989", "1 January 1988", "31 October 1993", "26 April 1986", "26 December 1991"],
    correctAnswer: 4
  }, {
    question: "What is the currency of Switzerland?",
    choices: ["franc", "Euro", "rupee", "won", "dollar"],
    correctAnswer: 0
  }, {
    question: "What is the square root of 256?",
    choices: [24, 25, 30, 26, 22],
    correctAnswer: 0
  }, {
    question: "What are the three main types of rocks?",
    choices: ['igneous, volcanic, quartz', 'sedimentary, igneous, metamorphic', 'feldspar, metamorphic, sedimentary', 'gargantuan, feldspar, quartz', 'None of the above'],
    correctAnswer: 1
  }, {
    question: "What movie did Leonardo DiCaprio win a BAFTA Film Award for?",
    choices: ['Inception', "What's Eating Gilbert Grape", 'The Revenant', 'The Wolf of Wall Street', 'He never got one.'],
    correctAnswer: 2
  }
  ];

  var questionCounter = 0; //Tracks question number
  var selections = []; //Array containing user choices
  var quiz = $('.content'); //Quiz div object

  // Display initial question
  displayNext();

  // Click handler for the 'next' button
  $('#next').on('click', function (e) {
    e.preventDefault();

    // Suspend click listener during fade animation
    if(quiz.is(':animated')) {        
      return false;
    }
    choose();

    // If no user selection, progress is stopped
    if (isNaN(selections[questionCounter])) {
      $('#warning').text('Please make a selection!');
    } else {
      questionCounter++;
      displayNext();
      $('#warning').text('');
    }
  });



  // Creates and returns the div that contains the questions and 
  // the answer selections
  function createQuestionElement(index) {
    var qElement = $('<div>', {
      id: 'question'
    });

    var header = $('<h2>Question ' + (index + 1) + ':</h2>');
    qElement.append(header);

    var question = $('<p>').append(questions[index].question);
    qElement.append(question);

    var radioButtons = createRadios(index);
    qElement.append(radioButtons);
    // this is new
    var warningText = $('<p id="warning">');
    qElement.append(warningText);

    return qElement;

  }

  // Creates a list of the answer choices as radio inputs
  function createRadios(index) {
    var radioList = $('<ul>');
    var item;
    var input = '';
    for (var i = 0; i < questions[index].choices.length; i++) {
      item = $('<li>');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += questions[index].choices[i];
      item.append(input);
      radioList.append(item);
    }
    return radioList;
  }

  // Reads the user selection and pushes the value to an array
  function choose() {
    selections[questionCounter] = +$('input[name="answer"]:checked').val();
  }

  // Displays next requested element
  function displayNext() {
    quiz.fadeOut(function() {
      $('#question').remove();

      if(questionCounter < questions.length){
        var nextQuestion = createQuestionElement(questionCounter);
        quiz.append(nextQuestion).fadeIn();
        if (!(isNaN(selections[questionCounter]))) {
          $('input[value='+selections[questionCounter]+']').prop('checked', true);
        }

        // Controls display of 'prev' button
        if(questionCounter === 1){
          $('#prev').show();
        } else if(questionCounter === 0){

          $('#prev').hide();
          $('#next').show();
        }
       }else {
        var scoreElem = displayScore();
        quiz.append(scoreElem).fadeIn();
        $('#next').hide();
        $('#prev').hide();
        $('#start').show();
      }
    });
  }

  // Computes score and returns a paragraph element to be displayed
  function displayScore() {
    var score = $('<h3>',{id: 'question'});

    var numCorrect = 0;
    for (var i = 0; i < selections.length; i++) {
      if (selections[i] === questions[i].correctAnswer) {
        numCorrect++;
      }
    }
    // Calculate score and display relevant message
    var percentage = numCorrect / questions.length;
    if (percentage >= 0.9){
        score.append('Incredible! You got ' + numCorrect + ' out of ' +
                 questions.length + ' questions right!');
    }

    else if (percentage >= 0.7){
        score.append('Good job! You got ' + numCorrect + ' out of ' +
                 questions.length + ' questions right!');
    }

    else if (percentage >= 0.5){
        score.append('You got ' + numCorrect + ' out of ' +
                 questions.length + ' questions right.');
    }

    else {
        score.append('You only got ' + numCorrect + ' out of ' +
                 questions.length + ' right. Want to try again?');
    }
    return score;
  }
});
$(文档).ready(函数(){
“严格使用”;
变量问题=[{
问题:“在物理学中,什么被定义为‘原子核结合形成更大质量原子核的核反应’?”,
选择:['裂变','聚变','发力','水力压裂','反常',
正确答案:1
}, {
问题:“澳大利亚的首都是什么?”,
选择:[“墨尔本”、“悉尼”、“堪培拉”、“昆士兰”、“基督城”],
正确答案:2
}, {
问:“谁是英国总理?”
选择:[“托尼·布莱尔”、“大卫·卡梅伦”、“尼古拉斯·萨科齐”、“戈登·布朗”、“约翰·梅杰爵士”],
正确答案:1
}, {
问题:“第一个完全数是什么?”,
选项:[38,6,0,256,28],
正确答案:1
}, {
问题:“挪威国旗上有什么颜色?”,
选择:[“红色和蓝色”、“红色和白色”、“红色、白色和银色”、“红色、白色和蓝色”、“蓝色和金色”],
正确答案:3
}, {
问题:“苏联是什么时候崩溃的?”,
选择:[“1989年2月14日”、“1988年1月1日”、“1993年10月31日”、“1986年4月26日”、“1991年12月26日”],
正确答案:4
}, {
问题:“瑞士的货币是什么?”,
选择:[“法郎”、“欧元”、“卢比”、“韩元”、“美元”],
正确答案:0
}, {
问题:“256的平方根是多少?”,
选项:[24,25,30,26,22],
正确答案:0
}, {
问题:“岩石的三种主要类型是什么?”,
选择:[“火成岩、火山岩、石英”、“沉积岩、火成岩、变质岩”、“长石、变质岩、沉积岩”、“巨大岩、长石、石英”、“上述任何一种”],
正确答案:1
}, {
问题:“莱昂纳多·迪卡普里奥凭借哪部电影获得英国电影艺术学院电影奖?”,
选择:[《盗梦空间》,《吉尔伯特葡萄是什么吃的》,《复仇者》,《华尔街的狼》,《他从来没有得到过》,
正确答案:2
}
];
var questionCounter=0;//跟踪问题编号
var selections=[];//包含用户选择的数组
var quick=$('.content');//quick div对象
//显示初始问题
displayNext();
//单击“下一步”按钮的处理程序
$(“#下一步”)。在('click',函数(e){
e、 预防默认值();
//在淡入淡出动画期间暂停单击侦听器
如果(quick.is(':animated'){
返回false;
}
选择();
//如果没有用户选择,则停止进度
if(isNaN(选择[问询计数器]){
$('警告').text('请选择!');
}否则{
问句器++;
displayNext();
$(“#警告”)。文本(“”);
}
});
//创建并返回包含问题和答案的div
//答案选择
函数createQuestionElement(索引){
变量qElement=$(''{
id:“问题”
});
var头=$('Question'+(index+1)+':');
追加(标题);
var question=$(“”).append(问题[index].question);
附加(问题);
var radioButtons=createRadios(索引);
qElement.append(单选按钮);
//这是新的
var warningText=$('

'); qElement.append(warningText); 返回元素; } //创建答案选项列表作为无线电输入 函数createRadios(索引){ var放射科医生=$(“

    ”); var项目; var输入=“”; 对于(var i=0;i”); 输入=''; 输入+=问题[索引]。选项[i]; 项目。追加(输入); 放射科医生。追加(项目); } 返回放射科医生; } //读取用户选择并将值推送到数组 函数选择(){ 选择[questionCounter]=+$('input[name=“answer”]:选中')。val(); } //显示下一个请求的元素 函数displayNext(){ 测验.淡出(函数(){ $(“#问题”).remove(); if(问询台