自訂確認 UI

htmx 支援 hx-confirm 屬性,提供一個簡單的機制來確認使用者動作。它使用 JavaScript 中預設的 confirm() 函式,雖然可靠,但可能與您的應用程式 UX 不一致。

在這個範例中,我們將看到如何使用 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 捕捉。

#原生 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 (!evt.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

這允許在提示中使用 hx-confirm 的值,當問題取決於元素時 (例如 django 列表) 很方便。

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

在此處深入了解 htmx:confirm 事件 這裡