2015-10-29 4 views
1

Я показываю два разных викторины на одной странице. У меня есть функция JS, которая повторяет все для второй викторины, единственное отличие - это около 5 переменных в начале второй функции.Как использовать ООП, чтобы избежать повторения одного и того же кода снова и снова?

Проблема в том, что если я хочу что-то исправить в ключевом коде викторины, мне придется делать это дважды (или больше, если позже я сделаю больше викторин).

Я бы не стал повторять основной код викторины снова и снова, вместо этого предоставляя только новые переменные каждый раз, когда я создаю новую викторину. Я читал об ООП, но я все еще чувствую, что над головой. Мне было интересно, может ли кто-нибудь представить пример того, что я должен делать.

В реальной версии викторины я использую внешний файл JSON для хранения данных викторины. Ниже я сохранил его в переменной для простоты.

Вот код: http://codepen.io/Jake_Ratliff/pen/QjrqRv?editors=001

же код здесь:

HTML:

<body> 

    <div id='main'> 

    <div id="question1"></div> 

    </div> 
    <br> 
    <div id='buttons'> 
    <button id='prev' class='button'>Back</button> 

    <button id='next' class='button'>Next</button><br><br> 
    <button id='restart' class='button'>Start Over?</button> 
    <br><br> 
    </div> 

    <div id='main2'> 

    <div id="question2"></div> 

    </div> 
    <br> 
    <div id='buttons'> 
    <button id='prev2' class='button'>Back</button> 

    <button id='next2' class='button'>Next</button><br><br> 
    <button id='restart2' class='button'>Start Over?</button> 
    <br><br> 
    </div> 

</body> 

JS:

quiz1(); 
quiz2(); 


function quiz1(){ 

    var allQuestions = [{ 
    question: "How many presidents were members of the Whig party?", 
    choices: ["Four", "Three", "Two"], 
    correct: 0 
}, { 
    question: "Who was the first president to be impeached?", 
    choices: ["Andrew Jackson", "Andrew Johnson", "Warren Harding"], 
    correct: 1 
}, { 
    question: "How many presidents died during their presidency?", 
    choices: ["Four", "Six", "Eight"], 
    correct: 2 
}]; 

var counter = 0; 
var main = $("#main"); 
var question = $("#question1"); 
var userInputs = []; 
var numCorrect = 0; 
var fadeSpeed = 700; 

var next = $("#next"); 
var prev = $("#prev"); 
var restart = $("#restart") 

createQDiv(); 

if (counter == 0) { 
    prev.hide(); 
} 

//click handler for Next Question button 
next.click(function() { 

    var selection = $("input[name=answer]:checked").val(); 
    if (selection != undefined) { 
    choose(); 
    fadeQuestion(); 
    setTimeout(function() { 
     clearLast(); 
     counter++; 
     //moveProgress(); 
     prev.show(); 
     createQDiv(); 
    }, fadeSpeed); 

    } else { 
    alert("You must select an answer to proceed.") 
    }; 
}); 

//creates question element 
function createQDiv() { 
    //$("#prev").hide(); 
    question.fadeIn(fadeSpeed); 
    main.append(question); 
    if (counter < 

    allQuestions.length 

) { 
    displayNext(); 
    } else { 
    displayScore(); 
    } 
}; 

//fade out question element 
function fadeQuestion() { 
    question.fadeOut(fadeSpeed); 
}; 

//clears question element 
function clearLast() { 
    question.empty(); 
}; 

//adds question and answers to question element 
function displayNext() { 
    restart.hide(); 
    var qPara = $("<p>" + allQuestions[counter].question + "</p>") 
    question.append(qPara); 
    createRadios(); 
    addPrevSelection(); 

}; 

//creates radio buttons for each choice 
function createRadios() { 
    var choices = allQuestions[counter].choices; 
    //var formElement = $("<form></form>"); 
    //$("#question").append(formElement); 
    for (i = 0; i < choices.length; i++) { 
    question.append($("<input type='radio' name='answer' value='" + i + "'>" + choices[i] + "<br>")); 
    }; 
}; 

//checks user's answer choice and stores in array 
function choose() { 
    var input = $("input[name=answer]:checked").val(); 

    userInputs[counter] = input; 

}; 

//create function for checking user's answers vs number correct. output = number of correct answers 
function correctAns() { 
    for (i = 0; i < allQuestions.length; i++) { 
    if (userInputs[i] == allQuestions[i].correct) { 
     numCorrect++; 
    }; 
    }; 
}; 
//create 'last page' for displaying user's score 

function displayScore() { 
    next.hide(); 
    prev.hide(); 
    correctAns(); 
    var score = (numCorrect/allQuestions.length); 
    //var encouragement; 
    var scoreElement = $("<p>You got " + numCorrect + " out of " + allQuestions.length + " correct.</p>"); 
    $("#question1").append(scoreElement); 
    restart.show(); 
}; 

prev.click(function() { 
    if (counter > 0) { 
    fadeQuestion(); 
    setTimeout(function() { 
     clearLast(); 
     counter--; 
     //moveProgress(); 
     createQDiv(); 
     addPrevSelection(); 
     choose(); 
    }, fadeSpeed); 

    //Cristina: what if user changes input and then hits back? It isn't kept, only logged on the next button. 
    } else { 
    prev.hide(); 
    } 
}); 

function addPrevSelection() { 
    var selection = userInputs[counter]; 
    var radioSelected = $("input[value='" + selection + "']"); 
    //alert(radioSelected); 
    radioSelected.prop("checked", true); 
}; 

restart.click(function() { 
    counter = 0; 
    next.show(); 
    userInputs = []; 
    numCorrect = 0; 
    clearLast(); 
    //moveProgress(); 
    createQDiv(); 

}); 

} 

function quiz2(){ 

    var allQuestions = [{ 
    question: "Sample text for second quiz?", 
    choices: ["Four", "Three", "Two"], 
    correct: 0 
}, { 
    question: "Sample text 2 for second quiz?", 
    choices: ["Andrew Jackson", "Andrew Johnson", "Warren Harding"], 
    correct: 1 
}, { 
    question: "Sample text 3?", 
    choices: ["Four", "Six", "Eight"], 
    correct: 2 
}]; 

var counter = 0; 
var main = $("#main2"); 
var question = $("#question2"); 
var userInputs = []; 
var numCorrect = 0; 
var fadeSpeed = 700; 

var next = $("#next2"); 
var prev = $("#prev2"); 
var restart = $("#restart2") 

createQDiv(); 

if (counter == 0) { 
    prev.hide(); 
} 

//click handler for Next Question button 
next.click(function() { 

    var selection = $("input[name=answer]:checked").val(); 
    if (selection != undefined) { 
    choose(); 
    fadeQuestion(); 
    setTimeout(function() { 
     clearLast(); 
     counter++; 
     //moveProgress(); 
     prev.show(); 
     createQDiv(); 
    }, fadeSpeed); 

    } else { 
    alert("You must select an answer to proceed.") 
    }; 
}); 

//creates question element 
function createQDiv() { 
    //$("#prev").hide(); 
    question.fadeIn(fadeSpeed); 
    main.append(question); 
    if (counter < 

    allQuestions.length 

) { 
    displayNext(); 
    } else { 
    displayScore(); 
    } 
}; 

//fade out question element 
function fadeQuestion() { 
    question.fadeOut(fadeSpeed); 
}; 

//clears question element 
function clearLast() { 
    question.empty(); 
}; 

//adds question and answers to question element 
function displayNext() { 
    restart.hide(); 
    var qPara = $("<p>" + allQuestions[counter].question + "</p>") 
    question.append(qPara); 
    createRadios(); 
    addPrevSelection(); 

}; 

//creates radio buttons for each choice 
function createRadios() { 
    var choices = allQuestions[counter].choices; 
    //var formElement = $("<form></form>"); 
    //$("#question").append(formElement); 
    for (i = 0; i < choices.length; i++) { 
    question.append($("<input type='radio' name='answer' value='" + i + "'>" + choices[i] + "<br>")); 
    }; 
}; 

//checks user's answer choice and stores in array 
function choose() { 
    var input = $("input[name=answer]:checked").val(); 

    userInputs[counter] = input; 

}; 

//create function for checking user's answers vs number correct. output = number of correct answers 
function correctAns() { 
    for (i = 0; i < allQuestions.length; i++) { 
    if (userInputs[i] == allQuestions[i].correct) { 
     numCorrect++; 
    }; 
    }; 
}; 
//create 'last page' for displaying user's score 

function displayScore() { 
    next.hide(); 
    prev.hide(); 
    correctAns(); 
    var score = (numCorrect/allQuestions.length); 
    //var encouragement; 
    var scoreElement = $("<p>You got " + numCorrect + " out of " + allQuestions.length + " correct.</p>"); 
    question.append(scoreElement); 
    restart.show(); 
}; 

prev.click(function() { 
    if (counter > 0) { 
    fadeQuestion(); 
    setTimeout(function() { 
     clearLast(); 
     counter--; 
     //moveProgress(); 
     createQDiv(); 
     addPrevSelection(); 
     choose(); 
    }, fadeSpeed); 

    //Cristina: what if user changes input and then hits back? It isn't kept, only logged on the next button. 
    } else { 
    prev.hide(); 
    } 
}); 

function addPrevSelection() { 
    var selection = userInputs[counter]; 
    var radioSelected = $("input[value='" + selection + "']"); 
    //alert(radioSelected); 
    radioSelected.prop("checked", true); 
}; 

restart.click(function() { 
    counter = 0; 
    next.show(); 
    userInputs = []; 
    numCorrect = 0; 
    clearLast(); 
    //moveProgress(); 
    createQDiv(); 

}); 

} 

ответ

2

Просто передать переменные в качестве параметра функции:

func quiz(allQuestions, num) { /* code here */ } 

quiz([{ 
    question: "How many presidents were members of the Whig party?", 
    choices: ["Four", "Three", "Two"], 
    correct: 0 
}, { 
    question: "Who was the first president to be impeached?", 
    choices: ["Andrew Jackson", "Andrew Johnson", "Warren Harding"], 
    correct: 1 
}, { 
    question: "How many presidents died during their presidency?", 
    choices: ["Four", "Six", "Eight"], 
    correct: 2 
}], 1); 
quiz([{ 
    question: "Sample text for second quiz?", 
    choices: ["Four", "Three", "Two"], 
    correct: 0 
}, { 
    question: "Sample text 2 for second quiz?", 
    choices: ["Andrew Jackson", "Andrew Johnson", "Warren Harding"], 
    correct: 1 
}, { 
    question: "Sample text 3?", 
    choices: ["Four", "Six", "Eight"], 
    correct: 2 
}], 2); 

http://codepen.io/anon/pen/VvdaQV?editors=001

+0

Если бы отрегулировать ручку, чтобы добавить «1» к кнопкам первой викторины: http://codepen.io/anon/pen/zvaqWP?editors=101 – Michael

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