确认请求
通常,你需要在发出请求之前确认操作。htmx 支持该 hx-confirm 属性,允许你使用简单的 javascript 实现对话框确认操作:
<button hx-delete="/account" hx-confirm="Are you sure you wish to delete your account?">
Delete My Account
</button>
使用该事件,你可以实现更复杂的确认对话框。确认示例 展示了如何使用 sweetalert2 库来确认 htmx 操作。
使用事件确认请求
另一个确认选项是通过 htmx:confirm 事件。此事件在请求的每个触发器上触发(而不仅仅是在具有 hx-confirm 属性的元素上),可用于实现请求的异步确认。
下面是对带有 confirm-with-sweet-alert='true' 属性的任何元素使用 sweet alert 的示例:
document.body.addEventListener('htmx:confirm', function(evt) {
if (evt.target.matches("[confirm-with-sweet-alert='true']")) {
evt.preventDefault();
swal({
title: "Are you sure?",
text: "Are you sure you are sure?",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((confirmed) => {
if (confirmed) {
evt.detail.issueRequest();
}
});
}
});