javascript - 如何使用js中的单独按钮删除表格行
问题描述
所以我正在创建一个表格,当我使用表格外的按钮关注单元格内的输入字段时,我需要能够删除一行
<div tabindex="0" class="remove_row" role="button" onclick="removeRow()">
<span>Remove</span>
</div>
<table id="ListTab" role="grid">
<thead tabindex="0">
<tr role="row">
<th title="Column 1" role="columnheader">
<span>Column 1</span>
</th>
<th title="Column 2" role="columnheader">
<span>Column 2</span>
</th>
</tr>
</thead>
<tbody tabindex="0">
<tr class="UiListRow">
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
</tr>
<tr class="UiListRow">
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
</tr>
<tr class="UiListRow">
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
</tr>
</tbody>
</table>
我希望当用户站在其中一个输入上并单击删除时,它只会删除该行。
解决方案
这对你有用吗?
var currentFocus = null;
document.querySelector('table').addEventListener("focusin", focusChanged);
function focusChanged(event) {
currentFocus = event.target;
}
function removeRow() {
if (currentFocus == null) {
return;
}
var rowToRemove = currentFocus.closest('tr');
if (rowToRemove.parentElement == null) {
return;
}
rowToRemove.parentElement.removeChild(rowToRemove);
}
<div tabindex="0" class="remove_row" role="button" onclick="removeRow()">
<span>Remove</span>
</div>
<table id="ListTab" role="grid">
<thead tabindex="0">
<tr role="row">
<th title="Column 1" role="columnheader">
<span>Column 1</span>
</th>
<th title="Column 2" role="columnheader">
<span>Column 2</span>
</th>
</tr>
</thead>
<tbody tabindex="0">
<tr class="UiListRow">
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off" placeholder="a">
</td>
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
</tr>
<tr class="UiListRow">
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off" placeholder="b">
</td>
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
</tr>
<tr class="UiListRow">
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off" placeholder="c">
</td>
<td tabindex="-1" role="gridcell">
<input type="text" autocomplete="off">
</td>
</tr>
</tbody>
</table>
推荐阅读
- python - 从 itertools 排列格式化打印
- javascript - 使用 Javascript 将 img 标签添加到 Django 模板中
- sharepoint - 如何在没有额外 chrome 的情况下嵌入 MS Planner 页面
- python - LambdaType 与 FunctionType
- ios - 对事件做出反应(而不是陈述!)
- google-apps-script - 如何使用 Google Scripts UrlFetchApp.fetch 从外部 API 获取字段?
- python - 为什么烧瓶不接受 JWT Cookie?
- android - 使用 Expo 备份 Android 密钥库 - 我们需要保存关联的密码吗?
- python - 无法在 google collab 中导入另一个 python 文件
- .net - 当服务停止时,是否需要拆除?