有一个通过 PHP 填充的表:
<table id="position">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Статус</th>
<th scope="col">IP-адрес</th>
<th scope="col">Последняя активность</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr id='{$ip}'>
<th scope='row'>{$id}</th>
<td>{$online}</td>
<td><a href='http://{$ip}' target='_blank'>{$ip}</a></td>
<td>{$lastActive}</td>
<td id='button'><i class='bi bi-trash' style='font-size: 20px' ;></i></td>
</tr>";
</tbody>
</table>
有点击表格行的跟踪:
const tbody = document.querySelector('#position tbody');
tbody.addEventListener('click', function (e) {
const cell = e.target.closest('td');
if (!cell) {return;} // Quit, not clicked on a cell
const row = cell.parentElement;
console.log(row.rowIndex, row.id);
问题是该函数跟踪对表格整行的点击,而我只需要最后一个单元格(带有id='button')。我尝试了几个选项 - 没有任何帮助 - 只跟踪了第一行的单元格,其余的被忽略了。
只需限定选择器
closest():不知何故,跟踪整个单元格的点击是不正常的。添加内部按钮或链接并单击它。
和 jquery(因为它在标签中)
如果动态添加行,则将 id 添加到 tbody
如果你真的需要直接点击单元格,那么
.remove将类转移到自身<td>,否则代码不会改变。一般来说,所有必要的单元格都需要用一个类标记并使用它。