【问题标题】:Angular - cannot access variable inside Jquery click functionAngular - 无法访问 Jquery click 函数中的变量
【发布时间】:2020-06-08 09:33:55
【问题描述】:

我有下面的 DataGrid 列 cellTemplate 编码为:

ctAccount(cellElement, cellInfo) {
 $('<div>')
      .appendTo(cellElement)
      .text(cellInfo.data.Other)
      .css('cursor', 'pointer')
      .on('click', function(event) {
             this.dDetail["aaa"] = { store: AspNetData.createStore({
                                                  key: "ID",
                                                  loadParams: { id: cellInfo.data.GroupID },
                                                  loadUrl: this.Svr.urlSuspect + "Group" 
                                              })
                                      };
       ...                      
       ...          

问题是编译器无法访问“this”(this.dDetail,this.Svr),因为“this”指的是“this: HTMLElement”,而不是指我的 Angular 项目。错误信息是

类型“HTMLElement”上不存在属性“xxx”。

如何在 this.dDetail 和 this.Svr 上编码?

【问题讨论】:

    标签: jquery angular devextreme


    【解决方案1】:

    将this 引用存储在正确范围内的变量中,然后在click 处理函数中使用该变量:

    ctAccount(cellElement, cellInfo) {
      let _this = this;
      $('<div>')
        .appendTo(cellElement)
        .text(cellInfo.data.Other)
        .css('cursor', 'pointer')
        .on('click', function(event) {
          _this.dDetail["aaa"] = {
            store: AspNetData.createStore({
              key: "ID",
              loadParams: {
                id: cellInfo.data.GroupID
              },
              loadUrl: _this.Svr.urlSuspect + "Group"
            })
          };
        });
      });
    }
    

    【讨论】:

    • 我尝试了 2 个解决方案,但编译没有问题,运行时错误:ERROR TypeError: Cannot read property 'dDetail' of undefined
    • 在这种情况下,听起来您希望this 的作用域比ctAccount() 函数的范围更大。使用与此答案中所述相同的方法,但只需在您拥有的代码的正确位置定义 _this。
    • 我尝试在开头添加:export class xxxComponent implements OnInit { _this = this;但没有效果!现在的错误是:找不到名称'_this'
    • 你忘了var(或者let,如果你支持ES6)
    【解决方案2】:

    你可以使用 ES6 arrow functions。

    喜欢

    ctAccount(cellElement, cellInfo) {
    
      .on('click', (event) => {
             this.dDetail["aaa"] = { store: AspNetData.createStore({
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2016-12-10
      • 1970-01-01
      • 2018-06-23
      相关资源
      最近更新 更多