我正在尝试使用parent('tr)和closest('tr') javascript方法并在选择下拉列表后获取表tr和第二个td值。但是我在google nut中搜索过但不起作用。如果有人知道请帮助找到解决方案。
app.component.html:
<table>
<thead>
<tr>
<td>Emp id</td>
<td>Roll id</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr>
<td>12345</td>
<td>18956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>18906</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>98956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>13956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
</tbody>
</table>
app.component.ts:
getTdValue(e){
let target = e.target.closest('tr');
if (target && target.id) {
let td = target.find('td:nth-child(2)');
if (td) {
console.log("Second td value is ="+ td.value )
}
}
}
https://stackblitz.com/edit/angular-peioe6?file=src/app/app.component.html
最佳答案
首先,您需要在 select
元素内有第二个 option
元素,以便触发任何更改事件。
<select (change)="getTdValue($event)">
<option></option>
<option>Get second td value of this row</option>
</select>
然后您可以重写您的 getTdValue
方法,如下所示:
getTdValue(mouseEvent: MouseEvent) {
let target = <HTMLSelectElement> mouseEvent.target;
let td = <HTMLTableCellElement> target.closest('tr').childNodes.item(1);
console.log("This row ID is " + td.innerHTML);
}
查看以下StackBlitz
更新
当 target.closest
不起作用时(Angular 6),可以用 target.parentElement.parentElement
替换,如下所示:
getTdValue(mouseEvent: MouseEvent) {
let target = <HTMLSelectElement> mouseEvent.target;
let td = <HTMLTableCellElement> target.parentElement.parentElement.childNodes.item(1);
console.log("This row ID is " + td.innerHTML);
}
关于javascript - 如何使用最接近的和 parent 的javascript方法来获取 Angular 6中的td值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59425556/