2013-03-29 2 views
0

hi im полностью noob в jquery im, пытающемся tokrt, поэтому я решил сделать динамическую викторину, чтобы улучшить свои навыки. Я делал это один шаг за раз, а затем попытался обернуть это все togheter. Я застрял в том, как проверить, что один из моих флажков проверен, чтобы сравнить, если он правильный ответ, а затем обновить вопрос и ответы. вот мой HTML:сравнение ответов в динамической викторине с jquery

<!DOCTYPE html> 
<html lang='es'> 
<head> 
<meta charset='UTF-8'> 
<title>Dynamic Quiz</title> 
<link rel="stylesheet" type="text/css" href="css/normalize.css"> 
<link rel="stylesheet" type="text/css" href="css/estilos.css"> 
<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript" src="js/prefixfree.js"></script> 
<script type="text/javascript" src="js/codigo.js"></script> 
</head> 
<body> 
<header> 
    <hgroup> 
     <h1>This is my Dynamic Quiz</h1> 
     <h2>Using html5/css/javascript</h2> 
    </hgruop> 
</header> 

<section id='description'> 
    <p>This quiz is compossed by 10 questions, you have to answer at least 7 
     from 10 to pass the exam.</p> 
    <h2>Lets start!</h2> 
</section> 

<div id='questions-number'> 
    <p>Question <span id='current-question'>1</span> of <span>10</span> </p> 
</div> 

<section id='questions'> 
    <p id='question'></p> 

    <ul> 
     <li><input type='checkbox' id='checkAnswer0'/><label id='answer0'>answer0</label></li> 
     <li><input type='checkbox' id='checkAnswer1'/><label id='answer1'>answer1</label></li> 
     <li><input type='checkbox' id='checkAnswer2'/><label id='answer2'>answer2</label></li> 
     <li><input type='checkbox' id='checkAnswer3'/><label id='answer3'>answer3</label></li> 
    </ul> 
</section> 

<div id='next'> 
    next 
</div> 
</body> 
</html> 

и это то, что я получил в JQuery до сих пор :)

$(document).on('ready', ready); 
function ready(){ 
var allQuestions = 
[ 
    { 
     question1: "Whats my real name?", 
     choices1: ["Jhonnatan", "Alberto", "Tatan","Jaime"], 
     answer1: 0 
    }, 

    { 
     question2: "Who is Colombia's president?", 
     choices2: ["Alvaro Uribe", "Andres Pastrana", "Juan Manuel Santos","Tatan"], 
     answer2: 2 
    }, 

    { 
     question3: "My favorite super heroe?", 
     choices3: ["Batman", "Flash", "Tatan","Javascript"], 
     answer3: 3 
    }, 

    { 
     question4: "Wich sports do i practice?", 
     choices4: ["Climbing", "Swimming", "Programming","Running"], 
     answer4: 0 
    }, 

    { 
     question5: "Whats my dad's name?", 
     choices5: ["Alberto", "Jorge", "Javier","Jose"], 
     answer5: 1 
    }, 

    { 
     question6: "Whats my favorite color?", 
     choices6: ["Red", "Purple", "Blue","All"], 
     answer6: 2 
    }, 

    { 
     question7: "My favorite alcoholic drink", 
     choices7: ["Vodka", "Aguardiente", "Rum","Tekila"], 
     answer7: 3 
    }, 

    { 
     question8: "Whats my favorite kind of music?", 
     choices8: ["Hardcore", "Reggaeton", "Salsa","Programming"], 
     answer8: 0 
    }, 

    { 
     question9: "How many qestions has this quiz??", 
     choices9: ["20", "8", "10","12"], 
     answer9: 2 
    }, 

    { 
     question10: "My favorite programming lenguage?", 
     choices10: ["Ruby", "Arduino", "Python","Javascript"], 
     answer10: 3 
    } 
]; 
var question = $('#question'); 
var choice1 = $('#answer0'); 
var choice2 = $('#answer1'); 
var choice3 = $('#answer2'); 
var choice4 = $('#answer3'); 

question.text(allQuestions[0].question1); 
choice1.text(allQuestions[0].choices1[0]); 
choice2.text(allQuestions[0].choices1[1]); 
choice3.text(allQuestions[0].choices1[2]); 
choice4.text(allQuestions[0].choices1[3]); 
console.log('funcionando!'); 

var next = $('#next'); 
next.on('click', changeQuestion); 
function changeQuestion(){ 
    var checked = $('#checkAnswer0'); 
    if($checked.prop('checked')){ 
     console.log('correcto')else{ 
      console.log('no es correctp'); 
     } 
    } 
} 
} 

я ценю вашу помощь, если вы поможете мне с этим! :)

+1

Почему бы вам не добавить атрибут значения к каждому из своих флажков и сравнить с ним - казалось бы, проще. Также казалось бы, что кнопки с радиоприемниками были бы более подходящими для этого, если бы это был множественный выбор? –

ответ

1

This example, похоже, делает то, что вы пытаетесь выполнить. Я пытался изменить как можно меньше кода, так что, надеюсь, это имеет смысл!

Например, намного проще итерации через объект/массив, когда ключи согласованы.

{ 
    question: "Whats my real name?", 
    choices: ["Jhonnatan", "Alberto", "Tatan","Jaime"], 
    answer: 0 
}, 

... instead of ... 

{ 
    question1: "Whats my real name?", 
    choices1: ["Jhonnatan", "Alberto", "Tatan","Jaime"], 
    answer1: 0 
}, 
+1

Я только что видел ваш пример im сделал что-то подобное ... плохо изучите свой код, чтобы лучше понять его и улучшить мою ... очень много –

1

Рад, что вы пытаетесь учиться. Есть много действий по очистке и эффективности, с которыми вы можете попрактиковаться, но вы можете найти проверенный элемент несколькими способами, например $(elem).is(':checked') или $(':checked'), чтобы найти все.

0

это, как я сделал это :) им Верри счастливы я это сделал, я только что видел @cmallard пример и, кажется, я все еще нужно улучшить некоторые вещи, также, кажется, что им в правильном пути ... если у вас есть какие-то предложения, я бы хотел их увидеть! :)

$(document).on('ready', ready); 
function ready(){ 
var allQuestions = 
[ 
    { 
     question: "Whats my real name?", 
     choices: ["Jhonnatan", "Alberto", "Tatan","Jaime"], 
     answer: 0 
    }, 

    { 
     question: "Who is Colombia's president?", 
     choices: ["Alvaro Uribe", "Andres Pastrana", "Juan Manuel Santos","Tatan"], 
     answer: 2 
    }, 

    { 
     question: "My favorite super heroe?", 
     choices: ["Batman", "Flash", "Tatan","Javascript"], 
     answer: 3 
    }, 

    { 
     question: "Wich sports do i practice?", 
     choices: ["Climbing", "Swimming", "Programming","Running"], 
     answer: 0 
    }, 

    { 
     question: "Whats my dad's name?", 
     choices: ["Alberto", "Jorge", "Javier","Jose"], 
     answer: 1 
    }, 

    { 
     question: "Whats my favorite color?", 
     choices: ["Red", "Purple", "Blue","All"], 
     answer: 2 
    }, 

    { 
     question: "My favorite alcoholic drink", 
     choices: ["Vodka", "Aguardiente", "Rum","Tekila"], 
     answer: 3 
    }, 

    { 
     question: "Whats my favorite kind of music?", 
     choices: ["Hardcore", "Reggaeton", "Salsa","Programming"], 
     answer: 0 
    }, 

    { 
     question: "How many qestions has this quiz??", 
     choices: ["20", "8", "10","12"], 
     answer: 2 
    }, 

    { 
     question: "My favorite programming lenguage?", 
     choices: ["Ruby", "Arduino", "Python","Javascript"], 
     answer: 3 
    } 
]; 

var number=0; 
var question = $('#question'); 
var choice1 = $('#answer0'); 
var choice2 = $('#answer1'); 
var choice3 = $('#answer2'); 
var choice4 = $('#answer3'); 
var next = $('#next'); 
var currentQuestion = $('#current-question'); 

next.on('click', changeQuestion); 
addQuestionAndAnswers();  



function addQuestionAndAnswers() { 
    currentQuestion.text(number + 1); 
    question.text(allQuestions[number].question); 
    choice1.text(allQuestions[number].choices[0]); 
    choice2.text(allQuestions[number].choices[1]); 
    choice3.text(allQuestions[number].choices[2]); 
    choice4.text(allQuestions[number].choices[3]); 
    console.log('funcionando!'); 
} 


function changeQuestion(){ 
    if(number!=9){ 
     if($("#myForm input[type='radio']:checked").val() == 
allQuestions[number].answer){ 
      number = number +1; 
      addQuestionAndAnswers(); 
     } else{ 
      console.log('respuesta errada'); 
     } 
    } else { 
     displayResult(); 
    } 


    function displayResult(){ 
     currentQuestion.text('10'); 
     $('#myForm').css('display', 'none'); 
     $('#question').css('display', 'none'); 
     $('#next').css('display', 'none'); 
     $('#score').css('display', 'inline-block') 
     $('#score').text('Your score is: ' + (number + 1) + 'pts'); 


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