推入数组在 jQuery 函数中不起作用

Pushing into array not working inside jQuery function

我正在使用 MaterializeCSS's autocomplete with Angular2-Materialize,我正在尝试将选定的值推入数组。但是,我收到以下错误:

Cannot read property 'push' of undefined

这是我的组件:

public items: any[] = [];

addItem() {
  $('.autocomplete-content').on('click', 'li', function () {
    let value = $(this).text().trim();
    this.items.push({ [value]: true });
  });
}

如果我在 jQuery 函数之外尝试 push 一些随机的东西,它会起作用。

这是我的 HTML:

<input type="text" (change)="addItem()" materialize="autocomplete" [materializeParams]="[{'data': myData | async}]">

this 在你的函数中指的是被点击的元素,而不是你的 class' 范围。所以要么使用 arrow function

 $('.autocomplete-content').on('click', 'li', ev => {
    let value = $(ev.target).text().trim();
    this.items.push({ [value]: true });
  });

bind(this) 使 class' 在 click 处理程序中可用

 $('.autocomplete-content').on('click', 'li', function (ev) {
    let value = $(ev.target).text().trim();
    this.items.push({ [value]: true });
  }.bind(this));

注意将 $(this) 更改为可以传递给函数的元素。

您还可以在 addItem() 中定义类似 that 的内容,然后使用它来代替...

addItem() {
  var that = this;  
  $('.autocomplete-content').on('click', 'li', function () {
    let value = $(this).text().trim();
    that.items.push({ [value]: true });
  });
}