htmx: onLoad: "on full page load" 和 "on after swap"
htmx: onLoad: "on full page load" and "on after swap"
我想用我自己的方法初始化一个 select
元素,就像在 tom-select Example 中一样:
<select id="select-repo" placeholder="Pick a repository..." multiple></select>
function my_select_init(el) {
new TomSelect(el, {
persist: false,
createOnBlur: true,
create: true
})
}
有两种不同的方式:
情况 1:加载整个页面
在这种情况下,您可以使用一种现代的 onLoad 方法。
例如:
document.addEventListener('DOMContentLoaded', function () {
// do something here ...
}, false);
案例 2:片段通过 htmx
插入到 DOM
如何初始化代码段?
首选方案
我希望 HTML 和加载代码位于一个位置 (Locality of Behaviour),并且我希望此 html 片段在两种情况下都相同。
到目前为止,我不使用 Hyperscript 或 Alpine.js,但我愿意使用这些库之一,如果这可以使解决方案更简单的话。
您要使用的是 htmx.onLoad
回调:
htmx.onLoad(function(elt) {
// look up all elements with the tomselect class on it within the element
var allSelects = htmx.findAll(elt, ".tomselect")
for( select of allSelects ) {
new TomSelect(select, {
persist: false,
createOnBlur: true,
create: true
});
}
})
此 javascript 将在页面加载到 body
元素时最初执行,然后对 htmx 添加到页面的所有新内容执行。
我想用我自己的方法初始化一个 select
元素,就像在 tom-select Example 中一样:
<select id="select-repo" placeholder="Pick a repository..." multiple></select>
function my_select_init(el) {
new TomSelect(el, {
persist: false,
createOnBlur: true,
create: true
})
}
有两种不同的方式:
情况 1:加载整个页面
在这种情况下,您可以使用一种现代的 onLoad 方法。
例如:
document.addEventListener('DOMContentLoaded', function () {
// do something here ...
}, false);
案例 2:片段通过 htmx
插入到 DOM如何初始化代码段?
首选方案
我希望 HTML 和加载代码位于一个位置 (Locality of Behaviour),并且我希望此 html 片段在两种情况下都相同。
到目前为止,我不使用 Hyperscript 或 Alpine.js,但我愿意使用这些库之一,如果这可以使解决方案更简单的话。
您要使用的是 htmx.onLoad
回调:
htmx.onLoad(function(elt) {
// look up all elements with the tomselect class on it within the element
var allSelects = htmx.findAll(elt, ".tomselect")
for( select of allSelects ) {
new TomSelect(select, {
persist: false,
createOnBlur: true,
create: true
});
}
})
此 javascript 将在页面加载到 body
元素时最初执行,然后对 htmx 添加到页面的所有新内容执行。