Closed. This question needs to be more focused。它当前不接受答案。
想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
4年前关闭。
我在同一页面上显示两个不同的测验。我有一个JS函数,它将对第二个测验重复所有操作,唯一不同的是在第二个函数的开头大约有5个变量。
这样做的问题是,如果我想修复核心测验代码中的某些内容,则必须做两次(如果以后再做更多测验,则需要做更多)。
我不想一遍又一遍地重复核心测验代码,而是每次我创建新测验时仅提供新变量。我已经阅读过有关OOP的文章,但我仍然感到头疼。我想知道是否有人可以提供我应该做的事的例子。
在真实版本的测验中,我使用外部JSON文件存储测验数据。为了简单起见,下面将其存储在变量中。
这是代码:http://codepen.io/Jake_Ratliff/pen/QjrqRv?editors=001
同样的代码在这里:
HTML:
JS:
http://codepen.io/anon/pen/VvdaQV?editors=001
想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
4年前关闭。
我在同一页面上显示两个不同的测验。我有一个JS函数,它将对第二个测验重复所有操作,唯一不同的是在第二个函数的开头大约有5个变量。
这样做的问题是,如果我想修复核心测验代码中的某些内容,则必须做两次(如果以后再做更多测验,则需要做更多)。
我不想一遍又一遍地重复核心测验代码,而是每次我创建新测验时仅提供新变量。我已经阅读过有关OOP的文章,但我仍然感到头疼。我想知道是否有人可以提供我应该做的事的例子。
在真实版本的测验中,我使用外部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();
});
}
最佳答案
只需将变量作为函数参数传递:
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
关于javascript - 如何使用OOP避免一遍又一遍地重复相同的代码? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33425907/
10-09 20:10