首页 > 解决方案 > 尝试获取选定的行索引时获取相同的索引

问题描述

我正在使用 Angular 并希望在用户单击时获取表内行的索引。当我尝试获取时,它总是返回 0。因为我只有一个tr内部tbody但即使我$('table td')仍然获得相同的索引。我应该改变什么?

HTML 中的表格

<table id="example" class="table table-striped">
        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Student Number</th>
            <th>Department</th>
            <th>Photo</th>
          </tr>
        </thead>
        <tbody *ngFor="let studentsEl of items2">
          <tr>
            <td>{{studentsEl.name}}</td>
            <td>{{studentsEl.age}}</td>
            <td>{{studentsEl.stuNumber}}</td>
            <td>{{studentsEl.department}}</td>
            <td>
                    <img
                    [src]="studentsEl.imagePath"
                    alt="{{ studentsEl.name }}"
                    class="img-responsive"
                    style="max-height: 75px;"> 
            </td>       
          </tr>
        </tbody>
      </table>

组件的打字稿文件

 constructor() {
    $(document).ready( function() {
      $('table tr').click( function() {
          alert($(this).index());
      }); 
  });

标签: htmlangulartypescript

解决方案


这里有几个问题:

  1. 用于ngFor表格行

  2. 您不应该dosument.ready在构造函数中使用,而是创建一个方法和click处理程序。

这是HTML:

<table id="example" class="table table-striped">
        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Student Number</th>
            <th>Department</th>
            <th>Photo</th>
          </tr>
        </thead>
        <tbody >
          <tr *ngFor="let studentsEl of items2; let idx = index">
            <td>
               <span (click)="getIndex(idx)">
                   {{studentsEl.name}} yourIndex: {{ idx  }}
               </span>
            </td>
            <td>{{studentsEl.age}}</td>
            <td>{{studentsEl.stuNumber}}</td>
            <td>{{studentsEl.department}}</td>
            <td>
                    <img
                    [src]="studentsEl.imagePath"
                    alt="{{ studentsEl.name }}"
                    class="img-responsive"
                    style="max-height: 75px;"> 
            </td>       
          </tr>
        </tbody>
      </table>

您的打字稿文件:

getIndex(idx){
    console.log(idx);
}

推荐阅读