此示例演示如何实现可编辑行。首先让我们看看表格主体
<table class="table delete-row-example">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody hx-target="closest tr" hx-swap="outerHTML">
...
</tbody>
</table>
这将告诉表格内的请求将目标定位到触发请求的最近的封闭行,并替换整行。
以下是行的 HTML 代码
<tr>
<td>${contact.name}</td>
<td>${contact.email}</td>
<td>
<button class="btn danger"
hx-get="/contact/${contact.id}/edit"
hx-trigger="edit"
onClick="let editing = document.querySelector('.editing')
if(editing) {
Swal.fire({title: 'Already Editing',
showCancelButton: true,
confirmButtonText: 'Yep, Edit This Row!',
text:'Hey! You are already editing a row! Do you want to cancel that edit and continue?'})
.then((result) => {
if(result.isConfirmed) {
htmx.trigger(editing, 'cancel')
htmx.trigger(this, 'edit')
}
})
} else {
htmx.trigger(this, 'edit')
}">
Edit
</button>
</td>
</tr>
这里我们变得有点花哨,只允许一次编辑一行,使用一些 JavaScript。我们检查是否有带有.editing
类的行,并确认用户是否要编辑此行并关闭其他行。如果是,我们会向其他行发送一个取消事件,以便它发出一个请求返回到其初始状态。
然后,我们在当前元素上触发edit
事件,这将触发 htmx 请求以获取行的可编辑版本。
请注意,如果您不关心用户是否正在编辑多行,您可以省略超脚本和自定义hx-trigger
,并让正常的点击处理与 htmx 协同工作。您也可以通过在单击“编辑”按钮时简单地定位整个表格来实现互斥。在这里,我们想展示如何集成 htmx 和 JavaScript 来解决问题,并缩小服务器交互范围,另外我们还可以使用一个不错的 SweetAlert 确认对话框。
最后,以下是在编辑数据时行的外观
<tr hx-trigger='cancel' class='editing' hx-get="/contact/${contact.id}">
<td><input name='name' value='${contact.name}'></td>
<td><input name='email' value='${contact.email}'></td>
<td>
<button class="btn danger" hx-get="/contact/${contact.id}">
Cancel
</button>
<button class="btn danger" hx-put="/contact/${contact.id}" hx-include="closest tr">
Save
</button>
</td>
</tr>
这里发生了一些事情:首先,行本身可以响应cancel
事件,这将恢复行的只读版本。有一个取消按钮允许取消当前编辑。最后,有一个保存按钮发出一个PUT
来更新联系人。请注意,有一个hx-include
包含最近行中的所有输入。表格行由于 HTML 限制而臭名昭著地难以与表单一起使用(您不能将form
直接放在tr
内),因此这使得处理起来更方便。