作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在构建一个小型测验应用程序,用户可以在其中构建自己的测验,但在 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 = new question(i, questionTitle, inputChoices, correctAnswer);
这行在它的范围内创建了另一个变量 question
即在点击事件处理程序。由于变量提升,它被移动到范围(函数)的顶部,最终变成:
$('#buildQuiz').click(function() {
var question; //undefined
...
...
//here question is not the one (constructor) in the outer scope but it is undefined in the inner scope.
question = new question(i, questionTitle, inputChoices, correctAnswer);
只需将变量名更改为其他名称并尝试。
var qn = new question(i, questionTitle, inputChoices, correctAnswer);
或者为了避免此类问题,您可以使用 Pascalcase 命名您的构造函数,即
var Question = function(questionNumber, question, choices, correctAnswer) {
.....
关于javascript - 未捕获的 TypeError : undefined is not a function, 在 for 循环中创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20620611/
我是一名优秀的程序员,十分优秀!