【问题标题】:Using TypeScript Variable Inside Jquery Each Loop在 Jquery 每个循环中使用 TypeScript 变量
【发布时间】:2019-08-09 01:10:40
【问题描述】:

我有一个名为 tableIndexNumber 的变量,我需要在不同的方法中使用它。因此,当我尝试访问该变量时,我使用“this.tableIndexNumber”并且可以访问它。但是我不能在 Jquery 每个循环中以这种方式使用它,因为 htmlElemets 在每个循环中也定义为“this”。那我应该走哪条路呢?

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');
  }
});

}

【问题讨论】:

标签: javascript jquery typescript


【解决方案1】:

处理此问题的老派方法是将this 保存到each 之前称为“上下文”或“那个”或类似名称的变量中,然后使用该变量。 幸运的是,今天我们有 arrow functions,它们非常适合这种情况,因为它们没有自己的 this 上下文。

更新:我忽略了查找each 的语法。看起来您需要内部的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');
          }
        });
    }
}

【讨论】:

  • 嘿扎克。首先非常感谢您的回答。我已经尝试过您的代码,但是当我运行它时,它总是转到“其他”部分。这样 ($(this).attr 不能作为正确的方式工作:/
  • 我的错,我应该先查一下 jQuery 方法。我已经更新了我的答案。
  • 谢谢。是否可以在 html 中调用该变量(“tableIndexNumber”)?
  • HTML 只处理一般格式。它对 JS 之类的变量或逻辑一无所知。如果您使用的是 Angular 或 React 之类的东西,它将包含一种模板语言,可以替代 HTML,并且您可以在其中插入逻辑。没有它,您将需要使用 JS 将变量插入到 DOM 中所需的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 2018-10-13
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多