我正在構建一個小型測驗應用程序,用戶可以在其中創建自己的測驗,但遇到了在for循環中創建對象的問題。Uncaught TypeError:undefined不是函數,在for循環中創建的對象
下面是提問對象的構造:
var question = function(questionNumber, question, choices, correctAnswer) {
this.questionNumber = questionNumber;
this.question = question;
this.choices = choices;
this.correctAnswer = correctAnswer; //The number stored here must be the location of the answer in the array
this.populateQuestions = function populateQuestions() {
var h2 = $('<h2>').append(this.question);
$('#quizSpace').append(h2);
for (var i = 0; i < choices.length; i++) {
//Create the input element
var radio = $('<input type="radio">').attr({value: choices[i], name: 'answer'});
//Insert the radio into the DOM
$('#quizSpace').append(radio);
radio.after('<br>');
radio.after(choices[i]);
}
};
allQuestions.push(this);
};
我有一個動態生成的,然後我拉離值,並將其放置在一個新的對象,像這樣一串HTML的:
$('#buildQuiz').click(function() {
var questionLength = $('.question').length;
for (var i = 1; i <= questionLength; i++) {
var questionTitle = $('#question' + i + ' .questionTitle').val();
var correctAnswer = $('#question' + i + ' .correctAnswer').val() - 1;
var inputChoices = [];
$('#question' + i + ' .choice').each(function(){
inputChoices.push($(this).val());
});
var question = new question(i, questionTitle, inputChoices, correctAnswer);
}
allQuestions[0].populateQuestions();
$('#questionBuilder').hide();
$('#quizWrapper').show();
});
然而,當我點擊#buildQuiz按鈕,我收到錯誤:
Uncaught TypeError: undefined is not a function
在此行中:
var question = new question(i, questionTitle, inputChoices, correctAnswer);
一個好的經驗法則對構造函數使用大寫字母。將'var question = function(...)'更改爲'var Question = function(...)'。 –