删除行

此示例展示了如何实现删除按钮,在完成后删除表行。首先让我们看一下表体:

¥This example shows how to implement a delete button that removes a table row upon completion. First let’s look at the table body:



<table class="table delete-row-example">
  <thead>
    <tr>
      <th>名称</th>
      <th>电子邮件</th> 
      <th>状态</th>
      <th></th>
    </tr>
  </thead>
  <tbody hx-confirm="Are you sure?" hx-target="closest tr" hx-swap="outerHTML swap:1s">
    ...
  </tbody>
</table>


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

¥The table body has a hx-confirm attribute to confirm the delete action. It also set the target to be the closest tr that is, the closest table row, for all the buttons (hx-target is inherited from parents in the DOM.) The swap specification in hx-swap says to swap the entire target out and to wait 1 second after receiving a response. This last bit is so that we can use the following CSS:

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

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

¥To fade the row out before it is swapped/removed.

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

¥Each row has a button with a hx-delete attribute containing the url on which to issue a DELETE request to delete the row from the server. This request responds with a 200 status code and empty content, indicating that the row should be replaced with nothing.

<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>
Server Requests ↑ Show

🔗Demo