【发布时间】:2020-04-03 14:11:18
【问题描述】:
我正在尝试为表格的第一列编写点击事件。如果我单击第一列 ID,我想在警报框中获取该值。我试过了,但它不起作用。 Rows 没有采用 Angular 7 和 8。
不要使用像#tableId 这样的元素引用。请使用表ID。
app.component.html:
<table id="tableId">
<thead>
<th>Id</th>
<th>Contact</th>
<th>Country</th>
</thead>
<tr>
<td>12345</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>12346</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>12347</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>12348</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>12349</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>12310</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
app.component.ts:
ngAfterViewInit() {
const table = <HTMLTableElement> document.getElementById('tableId');
for (let row of table.rows) {
const firstCell = row.childNodes.item(0);
firstCell.addEventListener('click', () => alert(firstCell.textContent));
(<HTMLElement> firstCell).setAttribute('style', 'cursor: pointer;');
}
}
【问题讨论】:
-
您只想获得任何行的第一个或单击
-
在我看来,这段代码适用于 Angular 8:stackblitz.com/edit/angular-mypspz?file=src/app/…
标签: javascript typescript angular7 angular8