htmx 支持 hx-confirm
属性,以提供确认用户操作的简单机制。这使用 javascript 中的默认 confirm()
函数,虽然可靠,但可能与你的应用 UX 不一致。
¥htmx supports the hx-confirm
attribute to provide a simple mechanism for confirming a user
action. This uses the default confirm()
function in javascript which, while trusty, may not be consistent with your
applications UX.
在此示例中,我们将了解如何使用 sweetalert2 实现自定义确认对话框。下面是两个示例,一个使用点击+自定义事件方法,另一个使用内置 hx-confirm
属性和 htmx:confirm
事件。
¥In this example we will see how to use sweetalert2 to implement a custom confirmation dialog. Below are two
examples, one using a click+custom event method, and one using the built-in hx-confirm
attribute and
the htmx:confirm
event.
¥Using on click+custom event
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<button hx-get="/confirmed"
hx-trigger='confirmed'
onClick="Swal.fire({title: 'Confirm', text:'Do you want to continue?'}).then((result)=>{
if(result.isConfirmed){
htmx.trigger(this, 'confirmed');
}
})">
Click Me
</button>
在这里,我们使用 javascript 在单击时显示 Sweet Alert 2,要求确认。如果用户确认对话框,我们将通过触发自定义 “confirmed” 事件来触发请求,然后由 hx-trigger
拾取该事件。
¥Here we use javascript to show a Sweet Alert 2 on a click, asking for confirmation. If the user confirms
the dialog, we then trigger the request by triggering the custom “confirmed” event
which is then picked up by hx-trigger
.
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("htmx:confirm", function(e) {
// The event is triggered on every trigger for a request, so we need to check if the element
// that triggered the request has a hx-confirm attribute, if not we can return early and let
// the default behavior happen
if (!e.detail.target.hasAttribute('hx-confirm')) return
// This will prevent the request from being issued to later manually issue it
e.preventDefault()
Swal.fire({
title: "Proceed?",
text: `I ask you... ${e.detail.question}`
}).then(function(result) {
if (result.isConfirmed) {
// If the user confirms, we manually issue the request
e.detail.issueRequest(true); // true to skip the built-in window.confirm()
}
})
})
</script>
<button hx-get="/confirmed" hx-confirm="Some confirm text here">
Click Me
</button>
我们添加一些 javascript 以在单击时调用 Sweet Alert 2,并要求确认。如果用户确认对话框,我们将通过调用 issueRequest
方法触发请求。我们将 skipConfirmation=true
作为参数传递以跳过 window.confirm
。
¥We add some javascript to invoke Sweet Alert 2 on a click, asking for confirmation. If the user confirms
the dialog, we trigger the request by calling the issueRequest
method. We pass skipConfirmation=true
as argument to skip window.confirm
.
这允许在提示中使用 hx-confirm
的值,这在问题依赖于元素(例如 django 列表)时很方便:
¥This allows to use hx-confirm
’s value in the prompt which is convenient
when the question depends on the element e.g. a django list:
{% for client in clients %} {% endfor %}
了解有关 htmx:confirm
事件 此处 的更多信息。
¥Learn more about the htmx:confirm
event here.