javascript - htmx:onLoad:“在整页加载”和“在交换后”
问题描述
我想用我自己的方法初始化一个类似于tom-select Exampleselect
的元素:
<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,但我愿意使用这些库之一,如果这使解决方案更简单的话。
解决方案
您要使用的是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
});
}
})
当页面加载到body
元素上时,此 javascript 将首先执行,然后为 htmx 添加到页面的所有新内容执行。
推荐阅读
- macos - 将 Font Awesome 加载到 FontBook 时出现问题
- reactjs - 如何在新窗口中打开 React Modal
- graphql - 如何在 GraphQL 中连接两种类型?
- apache - Ubuntu - 使用不同证书保护 *.mydomain.com 和 *.sub.mydomain.com 时遇到问题
- python - 字符串索引超出范围(长度错误不同)
- android - android 设备连接android studio 时无法识别,显示无法定位adb .. 什么问题?
- android - onItemSelectedListener 不适用于微调器 Kotlin
- python-3.x - 在 MPI azure ml 管道中运行 MPI python 脚本
- css - React-Bootstrap:使用 Font Awesome SVG 自定义 Navbar 的汉堡菜单
- javascript - 未经身份验证无法使用 nodemailer 发送电子邮件