此範例會在使用者輸入文字時即時搜尋聯絡人資料庫。
我們從一個搜尋輸入框和一個空的表格開始。
<h3>
Search Contacts
<span class="htmx-indicator">
<img src="/img/bars.svg"/> Searching...
</span>
</h3>
<input class="form-control" type="search"
name="search" placeholder="Begin Typing To Search Users..."
hx-post="/search"
hx-trigger="input changed delay:500ms, search"
hx-target="#search-results"
hx-indicator=".htmx-indicator">
<table class="table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody id="search-results">
</tbody>
</table>
當 input
事件觸發時,輸入框會向 /search
發出 POST
請求,並將表格的內容設定為返回的內容。請注意,也可以使用 keyup
事件,但如果使用者使用滑鼠貼上文字(或任何其他非鍵盤方式),則不會觸發。
我們在觸發器中添加了 delay:500ms
修飾符,以延遲發送查詢,直到使用者停止輸入。此外,我們還在觸發器中添加了 changed
修飾符,以確保當使用者沒有更改輸入值時(例如,他們按下方向鍵或貼上相同的值)不會發送新的查詢。
由於我們使用 search
類型的輸入框,輸入框中會出現一個 x
來清除輸入。要使此操作觸發新的 POST
請求,我們必須指定另一個觸發器。我們使用逗號分隔它們來指定另一個觸發器。當欄位被清除時,將執行 search
觸發器,但它也可以通過按 Enter 鍵來覆蓋 500 毫秒的 input
事件延遲。
最後,我們使用 hx-indicator
屬性來顯示搜尋正在進行中的指示器。