我在 javascript 类中有这个函数:
this.checkSections = function(){
jQuery('#droppable #section').each( function() {
nextId = jQuery(this).next().attr('id');
if (nextId != 'small' && nextId != 'large'){
jQuery(this).remove();
this.sections --;
this.followArticles = 0;
}else{
articles = 0;
obj = jQuery(this).next();
while (nextId == 'small' || nextId == 'large'){
articles++;
obj = obj.next()
nextId = obj.attr('id');
//alert(nextId);
}
this.followArticles = articles;
alert(this.sections);
}
});
}
alert(this.sections);
(最后几行)给出了undefined
的输出,尽管sections
已被定义和使用。
可能是什么问题?
最佳答案
this
始终是局部变量,因此它在每个函数中都会被覆盖。
您可能会做的是指向您的类(class),例如var myClass = this;
并使用 myClass
而不是 this
。
this.checkSections = function(){
var myClass = this;
jQuery('#droppable #section').each( function() {
nextId = jQuery(this).next().attr('id');
if (nextId != 'small' && nextId != 'large'){
jQuery(this).remove();
myClass.sections --;
myClass.followArticles = 0;
}else{
articles = 0;
obj = jQuery(this).next();
while (nextId == 'small' || nextId == 'large'){
articles++;
obj = obj.next()
nextId = obj.attr('id');
//alert(nextId);
}
myClass.followArticles = articles;
alert(myClass .sections);
}
});
}
关于javascript - 无法从 jquery 函数中访问 javascript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14562471/