删除行

此示例展示了如何实现一个删除按钮,该按钮在操作完成后会删除表格行。 首先,让我们看一下表格主体

<table class="table delete-row-example">
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Status</th>
      <th></th>
    </tr>
  </thead>
  <tbody hx-confirm="Are you sure?" hx-target="closest tr" hx-swap="outerHTML swap:1s">
    ...
  </tbody>
</table>

表格主体具有 hx-confirm 属性以确认删除操作。 它还将目标设置为最接近的 tr,即所有按钮的最接近的表格行(hx-target 从 DOM 中的父级继承)。 在 hx-swap 中的交换规范表示将整个目标交换出去,并在收到响应后等待 1 秒。 最后一个部分是为了让我们能够使用以下 CSS

tr.htmx-swapping td {
  opacity: 0;
  transition: opacity 1s ease-out;
}

在行被交换/删除之前将其淡出。

每一行都有一个带有 hx-delete 属性的按钮,其中包含用于发出 DELETE 请求以从服务器删除该行的 URL。 该请求以 200 状态码和空内容进行响应,表明该行应替换为空。

<tr>
  <td>Angie MacDowell</td>
  <td>angie@macdowell.org</td>
  <td>Active</td>
  <td>
    <button class="btn danger" hx-delete="/contact/1">
      Delete
    </button>
  </td>
</tr>
服务器请求 ↑ 显示
HTML

<table class="table delete-row-example">
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Status</th>
      <th></th>
    </tr>
  </thead>
  <tbody hx-confirm="Are you sure?" hx-target="closest tr" hx-swap="outerHTML swap:1s">
    <tr>
      <td>Joe Smith</td>
      <td>joe@smith.org</td>
      <td>Active</td>
      <td>
        <button class="btn danger" hx-delete="/contact/0">
          Delete
        </button>
      </td>
    </tr><tr>
      <td>Angi...

🔗演示

Name Email Status
Joe Smith joe@smith.org Active
Angie MacDowell angie@macdowell.org Active
Fuqua Tarkenton fuqua@tarkenton.org Active
Kim Yee kim@yee.org Inactive