我想用我自己的方法初始化一个select
元素,就像在tom-选择示例中一样:
<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代码位于一个地方(行为地点),并且我希望这个html片段对于这两种情况都是相同的。
到目前为止,我不使用Hyperscript或Alpine.js,但如果这使解决方案更简单的话,我愿意使用其中的一个库。
发布于 2021-06-15 16:19:21
您要使用的是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添加到页面的所有新内容执行。
https://stackoverflow.com/questions/67988846
复制相似问题