i有变量称为tableexnumber,我需要在奇异方法中使用。因此,当我尝试达到该变量时,我会使用" this.tableIndexnumber",我可以达到它。但是,由于HTMLELEMETS在每个循环中都定义为"此",因此我无法在每个循环中使用这种方式。那我应该遵循哪种方式?
export class TablesComponent implements OnInit {
tableIndexNumber = 1;
constructor() { }
change(col: number) {
$('#' + col).each(function () {
if ($(this).attr('class') === 'box') {
$(this).addClass('boxSelected');
this.tableIndexNumber ++;
} else {
$(this).removeClass('boxSelected').addClass('box');
}
});
}
处理此操作的旧学校方法是将this
保存到each
称为"上下文"或" that"或类似的东西之前,然后使用该变量。值得庆幸的今天,我们拥有箭头功能,这对于这种情况非常完美,因为它们没有自己的this
上下文。
更新:我忽略了每个人的语法。看起来您需要内部this
,因此箭头功能无法正常工作。相反,您可以通过将外部this
保存到变量来解决问题:
export class TablesComponent implements OnInit {
tableIndexNumber = 1;
constructor() { }
change(col: number) {
const component = this;
$('#' + col).each(function() {
if ($(this).attr('class') === 'box') {
$(this).addClass('boxSelected');
component.tableIndexNumber++;
} else {
$(this).removeClass('boxSelected').addClass('box');
}
});
}
}