【发布时间】:2013-12-16 20:49:07
【问题描述】:
我正在构建一个小型测验应用程序,用户可以在其中构建自己的测验,但在 for 循环中创建对象时遇到了问题。
这里是 Question 对象的构造函数:
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(...)。
标签: javascript jquery object