html - 尝试获取选定的行索引时获取相同的索引
问题描述
我正在使用 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());
});
});
解决方案
这里有几个问题:
用于
ngFor
表格行您不应该
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);
}
推荐阅读
- oracle - oracle中某些列的选择
- ratpack - 兼容的 Groovy 版本
- sql - 计算出现次数和出现次数的百分比
- vue.js - 从 vue.js 3 中传递数据的方法渲染组件
- vega - Vega:使画布适合容器宽度
- java - 如何使用 Apache POI 取消合并特定行中的单元格?
- python - Django rest 框架:序列化程序在响应数据中不包含 id 字段
- react-native - React Native 是否根据当前缩放因子缩放字体值?
- python - Flask2 应用返回版本冲突错误
- flutter - 在颤动中我们如何在更改图标颜色或背景颜色时编写 if () else if() else() ?