2014-09-20 3 views
-2

Я изучаю javascript (jquery), и я запрограммировал простую викторину. Я прошел долгий путь, и большинство, если оно функционирует так, как должно быть, мне трудно реализовать «проверенную» контрольную панель, чтобы позволить людям идти на следующий вопрос, когда они ответили на последний вопрос.Не удается включить отключенный атрибут в jquery

Весь тест на plunker: http://plnkr.co/edit/qIqa2mHtIOwZNGS2hSBd

отключить кнопку в функции questionmaker, используя следующую строку: $("<button>Next</button>").addClass("next").prop('disabled', true).insertAfter("form");

Соответствующий код JQuery:

var blaat = function() { 
     var isChecked = $('input[name=group1]:checked').length; 
     if (isChecked) { 
      $(".form").find(".next").prop('disabled', false); 
      var answer = $('input[name=group1]:checked', '#form').next().text(); 
      checkAnswer(answer); 
     } 
    }; 

Он никогда не стреляет эту линию : $(".form").find(".next").prop('disabled', false); Потому что, когда я помещаю эту строку в консоль с хромированием, она работает отлично. Что мне не хватает?

+0

Вы уверены, что в вашей форме есть класс 'form'? Вы упомянули его как «форму» ранее в коде – Clive

+0

. Вы не обрабатываете какое-либо событие, когда пользователь выбирает опцию. – melancia

+1

Вам нужно: '$ (". Form input "). On (" change ", blaat);' http://jsfiddle.net/hxre3vp5/ – melancia

ответ

0

Проблема заключается в том, что вы не прикрепляете обработчик к событию изменения параметров radio, поэтому всякий раз, когда пользователь выбирает ответ, ничего не происходит.

Вам просто нужно добавить этот бит в код:

$(".form input").on("change", blaat);

Я также сделал некоторые изменения, и окончательный код (предложение) будет выглядеть следующим образом:

$(function() { 
    var allQuestions; 

    allQuestions = [{ 
     question: "Who is Prime Minister of the United Kingdom?", 
     choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], 
     correctAnswer: 0 
    }, { 
     question: "Name the king who failed to keep an eye on things at the battle of Hastings ?", 
     choices: ["David Cameron", "Harold", "Winston Churchill", "Tony Blair"], 
     correctAnswer: 1 
    }, { 
     question: "In which sport would you use a chucker ?", 
     choices: ["Ice hockey", "Billiards", "Polo", "Curling"], 
     correctAnswer: 2 
    }, { 
     question: "If a snail climbed up a 12 ft wall at a steady rate of 3 feet a day, but slipped down 2ft every night, how many days would it take him to reach the top ?", 
     choices: ["10 days", "9 days", "8 days", "12 days"], 
     correctAnswer: 0 
    }, { 
     question: "Traditionally, what type of wood do Rolls Royce use on the dashboards of their cars?", 
     choices: ["Shit", "Gordon Brown", "Winston Churchill", "Walnut"], 
     correctAnswer: 3 
    }, { 
     question: "What is the national emblem of Canada ?", 
     choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Maple leaf"], 
     correctAnswer: 3 
    }, { 
     question: "Free Willey was a film about what ?", 
     choices: ["David Cameron", "Whale", "Winston Churchill", "Tony Blair"], 
     correctAnswer: 1 
    }, { 
     question: "What World War II operation was code named `Dynamo` ?", 
     choices: ["David Cameron", "Gordon Brown", "Evacuation of Dunkirk", "Tony Blair"], 
     correctAnswer: 2 
    }, { 
     question: "How many old pennies were there in a Groat?", 
     choices: ["One", "Two", "Three", "Four"], 
     correctAnswer: 3 
    }, { 
     question: "In cricket, where would you find the chain ?", 
     choices: ["Between the wickets", "Gordon Brown", "Winston Churchill", "Tony Blair"], 
     correctAnswer: 0 
    }]; 

    var correctAnswers = 0; 
    var currentQuestion = 0; 
    var answer = allQuestions[currentQuestion].choices[allQuestions[currentQuestion].correctAnswer]; 

    function init() { 
     var question = allQuestions[currentQuestion].question; 
     var $questions = $(".form input"); 

     $questions.each(function (index) { 
      var choices = allQuestions[currentQuestion].choices[index]; 
      $(this).next().text(choices); 
     }); 

     $("<h2></h2>").text(question).insertBefore("form"); 
     $("<button>Next</button>").addClass("next").prop("disabled",true).on('click', addView).insertAfter("form"); 
    } 

    function addView() { 
     var $input = $("#form").children(); // $('#form input') 

     currentQuestion++; 

     $("h2, button").remove(); 
     $input.prop('checked', false); 

     var question = allQuestions[currentQuestion].question;  
     var $questions = $(".form input"); 

     $questions.each(function (index) { 
      var choices = allQuestions[currentQuestion].choices[index]; 
      $(this).next().text(choices); 
     }); 

     $("<h2></h2>").text(question).insertBefore("form"); 
     $("<button>Next</button>").addClass("next").prop("disabled", true).on('click', addQuestion).insertAfter("form"); 
    } 

    function addQuestion() { 
     if (currentQuestion < 10) { 
      addView(); 
     } 
     else { 
      $(".next").on("click", function() { // need to write this function <-- 
       console.log("it worked!"); 
      }); 
     } 
    } 

    function blaat() { 
     var isChecked = $('input[name=group1]:checked').length; 

     if (isChecked) { 
      $(".form").find(".next").prop("disabled", false); 
      var answer = $('input[name=group1]:checked', '#form').next().text(); 
      checkAnswer(answer); 
     } 
    } 

    function checkAnswer(answer) {  
     var correctAnswer = allQuestions[currentQuestion].correctAnswer; 
     var indexAnswer = allQuestions[currentQuestion].choices[correctAnswer]; 

     if (indexAnswer == answer) { 
      correctAnswers++; 
      console.log(correctAnswers); 
      $(".record").text("You have answered " + correctAnswers + " questions correctly!"); 
      return answer; 
     } 
     else { 
      console.log("answer is not correct!"); 
     } 
    } 

    $("#start").on("click", function() { 
     $(".start").css("display", "none"); 
     $(".quiz").find(".form").removeClass("hidden"); 

     init(); 
    }); 

    $(".form input").on("change", blaat); 
}); 

Demo

+0

Спасибо, он исправил эту конкретную проблему, но теперь возникла новая ошибка. Теперь он обновляет значение correctответчиков также при каждом изменении (так что вы можете иметь 10 правильных ответов уже по первому вопросу), а не на событии клика следующей кнопки. Поэтому мне нужно найти способ проверить, был ли уже ответ на тот же вопрос, и если да, не обновляйте значение correctanswers. – sheez

+0

Если возникло другое требование, вам нужно открыть новый вопрос. Но я посмотрю на это через мгновение. – melancia

+0

Я решил все ошибки, которые пришли с ним! благодаря – sheez

0

Я вижу ваш код, попробуйте добавить $ ("input [type = 'radio']"). On ("click", blaat); in init function

Смежные вопросы