首页 > 解决方案 > 如何使用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>

我希望当用户站在其中一个输入上并单击删除时,它只会删除该行。

标签: javascripthtmlfrontend

解决方案


这对你有用吗?

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>


推荐阅读