我正在构建一个小型测验应用程序,用户可以在其中创建自己的测验,但遇到了在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(...)'。 –