Javascript API

虽然它不是库的重点,但 htmx 确实提供了一个小型辅助方法 API,主要用于 扩展开发 或与 events 配合使用。

¥While it is not a focus of the library, htmx does provide a small API of helper methods, intended mainly for extension development or for working with events.

hyperscript 项目旨在为基于 htmx 的应用提供更广泛的脚本支持。

¥The hyperscript project is intended to provide more extensive scripting support for htmx-based applications.

方法 - htmx.addClass()

¥Method - htmx.addClass()

此方法将一个类添加到给定的元素。

¥This method adds a class to the given element.

参数

¥Parameters

or

示例

¥Example

  // add the class 'myClass' to the element with the id 'demo'
  htmx.addClass(htmx.find('#demo'), 'myClass');

  // add the class 'myClass' to the element with the id 'demo' after 1 second
  htmx.addClass(htmx.find('#demo'), 'myClass', 1000);

方法 - htmx.ajax()

¥Method - htmx.ajax()

发出 htmx 样式的 AJAX 请求。此方法返回一个 Promise,因此可以在将内容插入 DOM 后执行回调。

¥Issues an htmx-style AJAX request. This method returns a Promise, so a callback can be executed after the content has been inserted into the DOM.

参数

¥Parameters

or

or

示例

¥Example

    // issue a GET to /example and put the response HTML into #myDiv
    htmx.ajax('GET', '/example', '#myDiv')

    // issue a GET to /example and replace #myDiv with the response
    htmx.ajax('GET', '/example', {target:'#myDiv', swap:'outerHTML'})

    // execute some code after the content has been inserted into the DOM
    htmx.ajax('GET', '/example', '#myDiv').then(() => {
      // this code will be executed after the 'htmx:afterOnLoad' event,
      // and before the 'htmx:xhr:loadend' event
      console.log('Content inserted successfully!');
    });

方法 - htmx.closest()

¥Method - htmx.closest()

查找给定元素父级中最接近的匹配元素,包括元素

¥Finds the closest matching element in the given elements parentage, inclusive of the element

参数

¥Parameters

示例

¥Example

  // find the closest enclosing div of the element with the id 'demo'
  htmx.closest(htmx.find('#demo'), 'div');

属性 - htmx.config

¥Property - htmx.config

保存 htmx 在运行时使用的配置的属性。

¥A property holding the configuration htmx uses at runtime.

请注意,使用 meta 标签 是设置这些属性的首选机制。

¥Note that using a meta tag is the preferred mechanism for setting these properties.

属性

¥Properties

示例

¥Example

  // update the history cache size to 30
  htmx.config.historyCacheSize = 30;

属性 - htmx.createEventSource

¥Property - htmx.createEventSource

用于创建新 服务器发送事件 源的属性。可以更新以提供自定义 SSE 设置。

¥A property used to create new Server Sent Event sources. This can be updated to provide custom SSE setup.

¥Value

示例

¥Example

  // override SSE event sources to not use credentials
  htmx.createEventSource = function(url) {
    return new EventSource(url, {withCredentials:false});
  };

属性 - htmx.createWebSocket

¥Property - htmx.createWebSocket

用于创建新 WebSocket 的属性。这可以更新以提供自定义 WebSocket 设置。

¥A property used to create new WebSocket. This can be updated to provide custom WebSocket setup.

¥Value

示例

¥Example

  // override WebSocket to use a specific protocol
  htmx.createWebSocket = function(url) {
    return new WebSocket(url, ['wss']);
  };

方法 - htmx.defineExtension()

¥Method - htmx.defineExtension()

定义一个新的 htmx extension

¥Defines a new htmx extension.

参数

¥Parameters

示例

¥Example

  // defines a silly extension that just logs the name of all events triggered
  htmx.defineExtension("silly", {
    onEvent : function(name, evt) {
      console.log("Event " + name + " was triggered!")
    }
  });

方法 - htmx.find()

¥Method - htmx.find()

查找与选择器匹配的元素

¥Finds an element matching the selector

参数

¥Parameters

or

示例

¥Example

    // find div with id my-div
    var div = htmx.find("#my-div")

    // find div with id another-div within that div
    var anotherDiv = htmx.find(div, "#another-div")

方法 - htmx.findAll()

¥Method - htmx.findAll()

查找与选择器匹配的所有元素

¥Finds all elements matching the selector

参数

¥Parameters

or

示例

¥Example

    // find all divs
    var allDivs = htmx.findAll("div")

    // find all paragraphs within a given div
    var allParagraphsInMyDiv = htmx.findAll(htmx.find("#my-div"), "p")

方法 - htmx.logAll()

¥Method - htmx.logAll()

记录所有 htmx 事件,对调试很有用。

¥Log all htmx events, useful for debugging.

示例

¥Example

    htmx.logAll();

方法 - htmx.logNone()

¥Method - htmx.logNone()

不记录 htmx 事件,如果之前启用了调试器,请调用此方法关闭它。

¥Log no htmx events, call this to turn off the debugger if you previously enabled it.

示例

¥Example

    htmx.logNone();

属性 - htmx.logger

¥Property - htmx.logger

htmx 用于记录的日志器

¥The logger htmx uses to log with

¥Value

示例

¥Example

    htmx.logger = function(elt, event, data) {
        if(console) {
            console.log("INFO:", event, elt, data);
        }
    }

方法 - htmx.off()

¥Method - htmx.off()

从元素中删除一个事件监听器

¥Removes an event listener from an element

参数

¥Parameters

or

示例

¥Example

    // remove this click listener from the body
    htmx.off("click", myEventListener);

    // remove this click listener from the given div
    htmx.off("#my-div", "click", myEventListener)

方法 - htmx.on()

¥Method - htmx.on()

向元素添加事件监听器

¥Adds an event listener to an element

参数

¥Parameters

or

示例

¥Example

    // add a click listener to the body
    var myEventListener = htmx.on("click", function(evt){ console.log(evt); });

    // add a click listener to the given div
    var myEventListener = htmx.on("#my-div", "click", function(evt){ console.log(evt); });

    // add a click listener to the given div that should only be invoked once
    var myEventListener = htmx.on("#my-div", "click", function(evt){ console.log(evt); }, { once: true });

方法 - htmx.onLoad()

¥Method - htmx.onLoad()

htmx:load 事件添加回调。这可用于处理新内容,例如使用 javascript 库初始化内容

¥Adds a callback for the htmx:load event. This can be used to process new content, for example initializing the content with a javascript library

参数

¥Parameters

示例

¥Example

    htmx.onLoad(function(elt){
        MyLibrary.init(elt);
    })

方法 - htmx.parseInterval()

¥Method - htmx.parseInterval()

解析与 htmx 方式一致的间隔字符串。对于具有时间相关属性的插件很有用。

¥Parses an interval string consistent with the way htmx does. Useful for plugins that have timing-related attributes.

警告:接受 int,后跟 sms。所有其他值都使用 parseFloat

¥Caution: Accepts an int followed by either s or ms. All other values use parseFloat

参数

¥Parameters

示例

¥Example

    // returns 3000
    var milliseconds = htmx.parseInterval("3s");

    // returns 3 - Caution
    var milliseconds = htmx.parseInterval("3m");

方法 - htmx.process()

¥Method - htmx.process()

处理新内容,启用 htmx 行为。如果你有在正常 htmx 请求周期之外添加到 DOM 的内容但仍希望 htmx 属性起作用,这将很有用。

¥Processes new content, enabling htmx behavior. This can be useful if you have content that is added to the DOM outside of the normal htmx request cycle but still want htmx attributes to work.

参数

¥Parameters

示例

¥Example

  document.body.innerHTML = "<div hx-get='/example'>Get it!</div>"
  // process the newly added content
  htmx.process(document.body);

方法 - htmx.remove()

¥Method - htmx.remove()

从 DOM 中删除一个元素

¥Removes an element from the DOM

参数

¥Parameters

or

示例

¥Example

  // removes my-div from the DOM
  htmx.remove(htmx.find("#my-div"));

  // removes my-div from the DOM after a delay of 2 seconds
  htmx.remove(htmx.find("#my-div"), 2000);

方法 - htmx.removeClass()

¥Method - htmx.removeClass()

从给定元素中删除一个类

¥Removes a class from the given element

参数

¥Parameters

or

示例

¥Example

  // removes .myClass from my-div
  htmx.removeClass(htmx.find("#my-div"), "myClass");

  // removes .myClass from my-div after 6 seconds
  htmx.removeClass(htmx.find("#my-div"), "myClass", 6000);

方法 - htmx.removeExtension()

¥Method - htmx.removeExtension()

从 htmx 中删除给定的扩展名

¥Removes the given extension from htmx

参数

¥Parameters

示例

¥Example

  htmx.removeExtension("my-extension");

方法 - htmx.swap()

¥Method - htmx.swap()

执行 HTML 内容的交换(和解决)

¥Performs swapping (and settling) of HTML content

参数

¥Parameters

示例

¥Example

    // swap #output element inner HTML with div element with "Swapped!" text
    htmx.swap("#output", "<div>Swapped!</div>", {swapStyle: 'innerHTML'});

方法 - htmx.takeClass()

¥Method - htmx.takeClass()

从其兄弟元素中获取给定的类,以便在其兄弟元素中,只有给定的元素才具有该类。

¥Takes the given class from its siblings, so that among its siblings, only the given element will have the class.

参数

¥Parameters

示例

¥Example

  // takes the selected class from tab2's siblings
  htmx.takeClass(htmx.find("#tab2"), "selected");

方法 - htmx.toggleClass()

¥Method - htmx.toggleClass()

在元素上切换给定类

¥Toggles the given class on an element

参数

¥Parameters

示例

¥Example

  // toggles the selected class on tab2
  htmx.toggleClass(htmx.find("#tab2"), "selected");

方法 - htmx.trigger()

¥Method - htmx.trigger()

在元素上触发给定事件

¥Triggers a given event on an element

参数

¥Parameters

示例

¥Example

  // triggers the myEvent event on #tab2 with the answer 42
  htmx.trigger("#tab2", "myEvent", {answer:42});

方法 - htmx.values()

¥Method - htmx.values()

返回通过 htmx 值解析机制解析给定元素的输入值

¥Returns the input values that would resolve for a given element via the htmx value resolution mechanism

参数

¥Parameters

示例

¥Example

  // gets the values associated with this form
  var values = htmx.values(htmx.find("#myForm"));