首页 > 解决方案 > jQuery回调函数中的打字稿代码

问题描述

我想将打字稿代码放在 jQuery 回调函数中。这是一个 Angular 6 组件 ts 文件。我使用 Material DataTable 作为 HTML 模板。当我单击一个按钮时,我想先让行淡出,然后更新 mongoDB,然后重新分页我的数据表。

现在在这个序列中,fadeOut 不能正常工作,因为更新函数不在 jQuery 的回调函数中(我猜)。

有人可以阐明一下吗?

谢谢

onSetOK(user: USER, i: number) {
  const index = this.dataSource.data.indexOf(user);
  console.log(index);

  //here begins the jQuery code to let the row fadeout
  $().ready(function() {
    const $row = $('#row' + i);
    $row.fadeOut(1000, function(e) {

      $row.remove();
      // put the below typescript code here
    });
  });

  //typescript code, update mongoDB
  this.service.updateUserOK(user).subscribe(res => {

    this.dataSource.data.splice(index, 1);
    this.dataSource.sort = this.sort;

    this.dataSource.paginator = this.paginator;

  });

}
...

<ng-container matColumnDef='Actions'>
  <mat-header-cell *matHeaderCellDef mat-sort-header> Actions </mat-header-cell>
  <mat-cell *matCellDef='let u, let i = index' (click)='$event.stopPropagation()'>
    <button mat-raised-button (click)='onSetOK(u, i)'>
      <i class='fas fa-check fa-2x'></i>
    </button>
  </mat-cell>
</ng-container>

<mat-row *matRowDef='let row; columns: getDisplayedColumns(); let i = index;' attr.id='row{{i}}'></mat-row>

标签: jqueryangulartypescriptangular-material

解决方案


您误用了 ready 功能。引用jQuery API 文档

描述:指定当 DOM 完全加载时要执行的函数。

因为此时您的 DOM 已完全加载,所以永远不会调用回调。只需像这样执行您的淡入淡出效果:

onSetOK(user: USER, i: number) {
  const index = this.dataSource.data.indexOf(user);
  console.log(index);

  //here begins the jQuery code to let the row fadeout
  const $row = $('#row' + i);
  $row.fadeOut(1000, (e) => {

    $row.remove();
    // put the below typescript code here

    //typescript code, update mongoDB
    this.service.updateUserOK(user).subscribe(res => {
      this.dataSource.data.splice(index, 1);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
    });
  });
}

推荐阅读