定制用户确认界面

htmx 支持 hx-confirm 属性,以提供确认用户操作的简单机制。使用javascript 中的默认函数 confirm(),虽然可靠,但可能与你的应用程序界面风格不一致。

在本例中我们将看到如何使用 sweetalert2 实现自定义确认对话框。下面是两个示例,一个使用点击+自定义事件方法,另一个使用内置 hx-confirm 属性和 htmx:confirm 事件。

使用点击+自定义事件

<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 接收。

Vanilla JS,hx-confirm

<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 作为参数传递给 skip window.confirm。

这里允许在提示中使用 hx-confirm 的值,当确认问题依赖于元素(例如 django 列表)时,这很方便:

{% for client in clients %}
<button hx-post="/delete/{{client.pk}}" hx-confirm="Delete {{client.name}}??">Delete</button>
{% endfor %}

在此了解有关 htmx:confirm 事件的更多信息。