HTMX - 擴充套件



HTMX 擴充套件用於操作此庫的行為,您可以在 JavaScript 中定義您的擴充套件,並透過 **hx-ext** 屬性使用該擴充套件。

如何使用擴充套件?

在 HTMX 中使用擴充套件非常簡單,您需要遵循兩個步驟。

  • **步驟 1:**您需要在 head 元素中新增一個擴充套件,這會將其新增到 htmx 擴充套件登錄檔中。
  • **步驟 2:**現在您必須在元素上使用 **hx-ext** 屬性來使用它。

HTMX 擴充套件示例

在此示例中,我們將向您展示如何透過 **hx-ext** 屬性使用預定義的擴充套件。

<script src="/tutorialspoint/htmx/debug.js" defer></script>

<div hx-ext="debug">
    <button hx-post="/content">Will Debug Code</button>
</div>

HTMX 忽略擴充套件

如果您在任何元素上使用了 **hx-ext** 屬性,那麼它將與該元素內部的所有子元素一起應用於 DOM 節點。有一種方法可以忽略擴充套件 htmx,假設您不希望在某些特定的子元素上應用您定義的擴充套件,那麼您必須使用 **ignore:** 關鍵字來阻止其使用。

<script src="/tutorialspoint/htmx/debug.js" defer></script>

<div hx-ext="debug">
    <button hx-post="/content">Will Debug Code</button>
    <button hx-post="/content" hx-ext="ignore:debug">Will Not Debug</button>
</div>

如何定義擴充套件?

要定義擴充套件,您需要使用 **htmx.defineExtension()** 函式,並且擴充套件始終應在單獨的檔案中建立。不要嘗試在內聯 **<script>** 標記中定義擴充套件。

<script>
    (function(){
        htmx.defineExtension('my-ext', {
            onEvent : function(name, evt) {
                console.log("Fired event: " + name, evt);
            }
        })
    })()
</script>

定義擴充套件的規則

如您在上面的程式碼中看到的,我們已經用最少的精力和程式碼定義了一個擴充套件。因此,在定義擴充套件時,您需要維護一些內容。

  • **擴充套件命名:**擴充套件的名稱應使用短橫線分隔,並且應足夠短且易於理解。
  • **覆蓋預設擴充套件:**擴充套件可以覆蓋預設擴充套件點以新增或更改功能。

擴充套件覆蓋預設擴充套件點

{
  init: function(api) { return null },
  getSelectors: function() { return null },
  onEvent: function(name, evt) { return true },
  transformResponse: function(text, xhr, elt) { return text },
  isInlineSwap: function(swapStyle) { return false },
  handleSwap: function(swapStyle, target, fragment, settleInfo) { return false },
  encodeParameters: function(xhr, parameters, elt) { return null }
}
廣告

© . All rights reserved.