事件

Htmx 提供了一个广泛的事件系统,可用于修改和增强行为。事件列在下面。

¥Htmx provides an extensive events system that can be used to modify and enhance behavior. Events are listed below.

事件 - htmx:abort

¥Event - htmx:abort

此事件与其他事件不同:htmx 不会触发它,而是监听它。

¥This event is different than other events: htmx does not trigger it, but rather listens for it.

如果你向发出请求的元素发送 htmx:abort 事件,它将中止请求:

¥If you send an htmx:abort event to an element making a request, it will abort the request:

<button id="request-button" hx-post="/example">Issue Request</button>
<button onclick="htmx.trigger('#request-button', 'htmx:abort')">Cancel Request</button>

事件 - htmx:afterOnLoad

¥Event - htmx:afterOnLoad

此事件在 AJAX onload 完成后触发。请注意,这并不意味着内容已被交换或解决,只表示请求已完成。

¥This event is triggered after an AJAX onload has finished. Note that this does not mean that the content has been swapped or settled yet, only that the request has finished.

详细信息

¥Details

事件 - htmx:afterProcessNode

¥Event - htmx:afterProcessNode

此事件在 htmx 初始化 DOM 节点后触发。它对于在节点上构建附加功能的扩展很有用。

¥This event is triggered after htmx has initialized a DOM node. It can be useful for extensions to build additional features onto a node.

详细信息

¥Details

事件 - htmx:afterRequest

¥Event - htmx:afterRequest

此事件在 AJAX 请求完成后触发,无论是在请求成功的情况下(尽管可能返回了远程错误代码,例如 404)还是在网络错误的情况下。此事件可以与 htmx:beforeRequest 配对,以围绕请求周期封装行为。

¥This event is triggered after an AJAX request has finished either in the case of a successful request (although one that may have returned a remote error code such as a 404) or in a network error situation. This event can be paired with htmx:beforeRequest to wrap behavior around a request cycle.

详细信息

¥Details

事件 - htmx:afterSettle

¥Event - htmx:afterSettle

此事件在 DOM 具有 settled 后触发。

¥This event is triggered after the DOM has settled.

详细信息

¥Details

事件 - htmx:afterSwap

¥Event - htmx:afterSwap

此事件在新内容 交换到 DOM 后触发。

¥This event is triggered after new content has been swapped into the DOM.

详细信息

¥Details

事件 - htmx:beforeCleanupElement

¥Event - htmx:beforeCleanupElement

此事件在 htmx disables 元素或将其从 DOM 中删除之前触发。

¥This event is triggered before htmx disables an element or removes it from the DOM.

详细信息

¥Details

事件 - htmx:beforeOnLoad

¥Event - htmx:beforeOnLoad

此事件在任何响应处理发生之前触发。如果你在事件上调用 preventDefault() 来取消它,则不会发生交换。

¥This event is triggered before any response processing occurs. If you call preventDefault() on the event to cancel it, no swap will occur.

详细信息

¥Details

事件 - htmx:beforeProcessNode

¥Event - htmx:beforeProcessNode

此事件在 htmx 初始化 DOM 节点并处理完其所有 hx- 属性之前触发。这使扩展和其他外部代码能够在处理 DOM 节点之前修改其内容。

¥This event is triggered before htmx initializes a DOM node and has processed all of its hx- attributes. This gives extensions and other external code the ability to modify the contents of a DOM node before it is processed.

详细信息

¥Details

事件 - htmx:beforeRequest

¥Event - htmx:beforeRequest

此事件在发出 AJAX 请求之前触发。如果你在事件上调用 preventDefault() 来取消它,则不会发生任何请求。

¥This event is triggered before an AJAX request is issued. If you call preventDefault() on the event to cancel it, no request will occur.

详细信息

¥Details

事件 - htmx:beforeSend

¥Event - htmx:beforeSend

此事件在发送请求之前立即触发。你不能使用此事件取消请求。

¥This event is triggered right before a request is sent. You may not cancel the request with this event.

详细信息

¥Details

事件 - htmx:beforeSwap

¥Event - htmx:beforeSwap

此事件在任何新内容 交换到 DOM 之前触发。除了响应标头优先的情况外,detail 上的大多数值都可以设置为覆盖后续行为。如果你在事件上调用 preventDefault() 来取消它,则不会发生交换。

¥This event is triggered before any new content has been swapped into the DOM. Most values on detail can be set to override subsequent behavior, other than where response headers take precedence. If you call preventDefault() on the event to cancel it, no swap will occur.

你可以通过修改事件详细信息的 shouldSwapselectOverrideswapOverridetarget 属性来修改默认交换行为。有关更多详细信息,请参阅 配置交换 上的文档。

¥You can modify the default swap behavior by modifying the shouldSwap, selectOverride, swapOverride and target properties of the event detail. See the documentation on configuring swapping for more details.

详细信息

¥Details

事件 - htmx:beforeTransition

¥Event - htmx:beforeTransition

此事件在 查看转换 封装交换发生之前触发。如果你在事件上调用 preventDefault() 来取消它,则不会发生视图转换,而是会发生正常的交换逻辑。

¥This event is triggered before a View Transition wrapped swap occurs. If you call preventDefault() on the event to cancel it, the View Transition will not occur and the normal swapping logic will happen instead.

详细信息

¥Details

事件 - htmx:configRequest

¥Event - htmx:configRequest

此事件在 htmx 收集了要包含在请求中的参数后触发。它可用于包含或更新 htmx 将发送的参数:

¥This event is triggered after htmx has collected parameters for inclusion in the request. It can be used to include or update the parameters that htmx will send:

document.body.addEventListener('htmx:configRequest', function(evt) {
    evt.detail.parameters['auth_token'] = getAuthToken(); // add a new parameter into the mix
});

请注意,如果输入值出现多次,则 parameters 对象中的值将是一个数组,而不是单个值。

¥Note that if an input value appears more than once the value in the parameters object will be an array, rather than a single value.

详细信息

¥Details

事件 - htmx:confirm

¥Event - htmx:confirm

此事件在请求的每个触发器上触发(不仅仅是在具有 hx-confirm 属性的元素上)。它允许你取消(或延迟)发出 AJAX 请求。如果你在事件上调用 preventDefault(),它将不会发出给定的请求。detail 对象包含一个函数 evt.detail.issueRequest(skipConfirmation=false),可用于在稍后发出实际的 AJAX 请求。结合这两个功能,你可以创建异步确认对话框。

¥This event is fired on every trigger for a request (not just on elements that have a hx-confirm attribute). It allows you to cancel (or delay) issuing the AJAX request. If you call preventDefault() on the event, it will not issue the given request. The detail object contains a function, evt.detail.issueRequest(skipConfirmation=false), that can be used to issue the actual AJAX request at a later point. Combining these two features allows you to create an asynchronous confirmation dialog.

以下是一个基本示例,展示了 htmx:confirm 事件的基本用法,而不改变默认行为:

¥Here is a basic example that shows the basic usage of the htmx:confirm event without altering the default behavior:

document.body.addEventListener('htmx:confirm', function(evt) {
  // 0. To modify the behavior only for elements with the hx-confirm attribute,
  //    check if evt.detail.target.hasAttribute('hx-confirm')

  // 1. Prevent the default behavior (this will prevent the request from being issued)
  evt.preventDefault();
  
  // 2. Do your own logic here
  console.log(evt.detail)

  // 3. Manually issue the request when you are ready
  evt.detail.issueRequest(); // or evt.detail.issueRequest(true) to skip the built-in window.confirm()
});

以下是在任何具有 confirm-with-sweet-alert="{question}" 属性的元素上使用 甜蜜警报 的示例:

¥And here is an example using sweet alert on any element with a confirm-with-sweet-alert="{question}" attribute on it:

document.body.addEventListener('htmx:confirm', function(evt) {
  // 1. The requirement to show the sweet alert is that the element has a confirm-with-sweet-alert
  //    attribute on it, if it doesn't we can return early and let the default behavior happen
  if (!evt.detail.target.hasAttribute('confirm-with-sweet-alert')) return

  // 2. Get the question from the attribute
  const question = evt.detail.target.getAttribute('confirm-with-sweet-alert');

  // 3. Prevent the default behavior (this will prevent the request from being issued)
  evt.preventDefault();

  // 4. Show the sweet alert
  swal({
    title: "Are you sure?",
    text: question || "Are you sure you want to continue?",
    icon: "warning",
    buttons: true,
    dangerMode: true,
  }).then((confirmed) => {
    if (confirmed) {
      // 5. If the user confirms, we can manually issue the request
      evt.detail.issueRequest(true); // true to skip the built-in window.confirm()
    }
  });
});

详细信息

¥Details

事件 - htmx:historyCacheError

¥Event - htmx:historyCacheError

当尝试将缓存保存到 localStorage 失败时触发此事件

¥This event is triggered when an attempt to save the cache to localStorage fails

详细信息

¥Details

事件 - htmx:historyCacheMiss

¥Event - htmx:historyCacheMiss

当恢复历史记录时发生缓存未命中时会触发此事件

¥This event is triggered when a cache miss occurs when restoring history

详细信息

¥Details

事件 - htmx:historyCacheMissError

¥Event - htmx:historyCacheMissError

当发生缓存未命中并且已从服务器检索到要恢复的内容的响应,但响应为错误(例如 404)时会触发此事件

¥This event is triggered when a cache miss occurs and a response has been retrieved from the server for the content to restore, but the response is an error (e.g. 404)

详细信息

¥Details

事件 - htmx:historyCacheMissLoad

¥Event - htmx:historyCacheMissLoad

当发生缓存未命中并且已成功从服务器检索到要恢复的内容的响应时会触发此事件

¥This event is triggered when a cache miss occurs and a response has been retrieved successfully from the server for the content to restore

详细信息

¥Details

事件 - htmx:historyRestore

¥Event - htmx:historyRestore

当 htmx 处理历史记录恢复操作时,将触发此事件

¥This event is triggered when htmx handles a history restoration action

详细信息

¥Details

事件 - htmx:beforeHistorySave

¥Event - htmx:beforeHistorySave

此事件在内容保存到历史 api 之前触发。

¥This event is triggered before the content is saved in the history api.

详细信息

¥Details

事件 - htmx:load

¥Event - htmx:load

当 htmx 将新节点加载到 DOM 中时,会触发此事件。

¥This event is triggered when a new node is loaded into the DOM by htmx.

详细信息

¥Details

事件 - htmx:noSSESourceError

¥Event - htmx:noSSESourceError

当元素在其触发器中引用 SSE 事件但未定义父 SSE 源时,将触发此事件

¥This event is triggered when an element refers to an SSE event in its trigger, but no parent SSE source has been defined

详细信息

¥Details

事件 - htmx:oobAfterSwap

¥Event - htmx:oobAfterSwap

此事件作为 带外交换 的一部分触发,其行为与 交换事件后 相同

¥This event is triggered as part of an out of band swap and behaves identically to an after swap event

详细信息

¥Details

事件 - htmx:oobBeforeSwap

¥Event - htmx:oobBeforeSwap

此事件作为 带外交换 的一部分触发,其行为与 交换事件前 相同

¥This event is triggered as part of an out of band swap and behaves identically to a before swap event

详细信息

¥Details

事件 - htmx:oobErrorNoTarget

¥Event - htmx:oobErrorNoTarget

带外交换 在 DOM 中没有相应的元素可以切换时触发此事件。

¥This event is triggered when an out of band swap does not have a corresponding element in the DOM to switch with.

详细信息

¥Details

事件 - htmx:onLoadError

¥Event - htmx:onLoadError

load 处理 AJAX 调用期间发生错误时,将触发此事件

¥This event is triggered when an error occurs during the load handling of an AJAX call

详细信息

¥Details

事件 - htmx:prompt

¥Event - htmx:prompt

此事件在向用户显示具有 hx-prompt 属性的提示后触发。如果取消此事件,则不会发生 AJAX 请求。

¥This event is triggered after a prompt has been shown to the user with the hx-prompt attribute. If this event is cancelled, the AJAX request will not occur.

详细信息

¥Details

事件 - htmx:beforeHistoryUpdate

¥Event - htmx:beforeHistoryUpdate

此事件在执行历史记录更新之前触发。它可用于修改用于更新历史记录的 pathtype

¥This event is triggered before a history update is performed. It can be used to modify the path or type used to update the history.

详细信息

¥Details

事件 - htmx:pushedIntoHistory

¥Event - htmx:pushedIntoHistory

此事件在 URL 被推送到历史记录后触发。

¥This event is triggered after a URL has been pushed into history.

详细信息

¥Details

事件 - htmx:replacedInHistory

¥Event - htmx:replacedInHistory

此事件在 URL 在历史记录中被替换后触发。

¥This event is triggered after a URL has been replaced in history.

详细信息

¥Details

事件 - htmx:responseError

¥Event - htmx:responseError

当发生 HTTP 错误响应时触发此事件

¥This event is triggered when an HTTP error response occurs

详细信息

¥Details

事件 - htmx:sendAbort

¥Event - htmx:sendAbort

当请求中止时,会触发此事件

¥This event is triggered when a request is aborted

详细信息

¥Details

事件 - htmx:sendError

¥Event - htmx:sendError

当网络错误阻止 HTTP 请求发生时,会触发此事件

¥This event is triggered when a network error prevents an HTTP request from occurring

详细信息

¥Details

事件 - htmx:sseError

¥Event - htmx:sseError

当 SSE 源发生错误时,将触发此事件

¥This event is triggered when an error occurs with an SSE source

详细信息

¥Details

事件 - htmx:swapError

¥Event - htmx:swapError

当交换阶段发生错误时,将触发此事件

¥This event is triggered when an error occurs during the swap phase

详细信息

¥Details

事件 - htmx:targetError

¥Event - htmx:targetError

当对 hx-target 属性使用错误的选择器时(例如,元素 ID 前面没有 #)会触发此事件

¥This event is triggered when a bad selector is used for a hx-target attribute (e.g. an element ID without a preceding #)

详细信息

¥Details

事件 - htmx:timeout

¥Event - htmx:timeout

当发生请求超时时,会触发此事件。这封装了 XMLHttpRequest 的典型 timeout 事件。

¥This event is triggered when a request timeout occurs. This wraps the typical timeout event of XMLHttpRequest.

可以使用 htmx.config.timeout 或每个元素使用 hx-request 设置超时时间

¥Timeout time can be set using htmx.config.timeout or per element using hx-request

详细信息

¥Details

事件 - htmx:trigger

¥Event - htmx:trigger

每当有 AJAX 请求时,都会触发此事件,即使未指定 AJAX 请求。它主要用于允许 hx-trigger 执行客户端脚本;AJAX 请求具有更细粒度的事件可用,例如 htmx:beforeRequesthtmx:afterRequest

¥This event is triggered whenever an AJAX request would be, even if no AJAX request is specified. It is primarily intended to allow hx-trigger to execute client-side scripts; AJAX requests have more granular events available, like htmx:beforeRequest or htmx:afterRequest.

详细信息

¥Details

事件 - htmx:validateUrl

¥Event - htmx:validateUrl

此事件在发出请求之前触发,允许你验证 htmx 将要请求的 URL。如果在事件上调用 preventDefault(),则不会发出请求。

¥This event is triggered before a request is made, allowing you to validate the URL that htmx is going to request. If preventDefault() is invoked on the event, the request will not be made.

document.body.addEventListener('htmx:validateUrl', function (evt) {
  // only allow requests to the current server as well as myserver.com
  if (!evt.detail.sameHost && evt.detail.url.hostname !== "myserver.com") {
    evt.preventDefault();
  }
});

详细信息

¥Details

事件 - htmx:validation:validate

¥Event - htmx:validation:validate

此事件在验证元素之前触发。它可以与 elt.setCustomValidity() 方法一起使用来实现自定义验证规则。

¥This event is triggered before an element is validated. It can be used with the elt.setCustomValidity() method to implement custom validation rules.

<form hx-post="/test">
  <input _="on htmx:validation:validate
               if my.value != 'foo'
                  call me.setCustomValidity('Please enter the value foo')
               else
                  call me.setCustomValidity('')"
         name="example">
</form>

详细信息

¥Details

事件 - htmx:validation:failed

¥Event - htmx:validation:failed

当元素验证失败时触发此事件。

¥This event is triggered when an element fails validation.

详细信息

¥Details

事件 - htmx:validation:halted

¥Event - htmx:validation:halted

当请求由于验证错误而停止时,会触发此事件。

¥This event is triggered when a request is halted due to validation errors.

详细信息

¥Details

事件 - htmx:xhr:abort

¥Event - htmx:xhr:abort

当 ajax 请求中止时触发此事件

¥This event is triggered when an ajax request aborts

详细信息

¥Details

事件 - htmx:xhr:loadstart

¥Event - htmx:xhr:loadstart

当 ajax 请求开始时触发此事件

¥This event is triggered when an ajax request starts

详细信息

¥Details

事件 - htmx:xhr:loadend

¥Event - htmx:xhr:loadend

当 ajax 请求完成时触发此事件

¥This event is triggered when an ajax request finishes

详细信息

¥Details

事件 - htmx:xhr:progress

¥Event - htmx:xhr:progress

当支持进度的 ajax 请求正在进行时,会定期触发此事件

¥This event is triggered periodically when an ajax request that supports progress is in flight

详细信息

¥Details