【发布时间】:2022-08-03 02:13:54
【问题描述】:
我在根级别有一个 Web 组件。其简化版如下图所示:
class AppLayout {
constructor() {
super();
this.noShadow = true;
}
connectedCallback() {
super.connectedCallback();
this.render();
this.insertAdjacentHTML(\"afterbegin\", this.navigation);
}
render() {
this.innerHTML = this.template;
}
get template() {
return `
<h1>Hello</h1>
`;
}
navigation = `
<script type=\"module\">
import \'./components/nav-bar.js\'
</script>
`;
}
customElements.define(\'app-layout\', AppLayout);
我想在这个组件加载后加载一个脚本。该脚本为导航创建 html 并尝试将其添加到上面显示的 app-layout 元素中。然而,即使它确实找到了app-layout 元素,它也无法附加navBar 元素。但是,它可以将navBar 附加到html 的body。任何我想念的想法。
const navLinks =
`<ul>
<li>Some</li>
<li>Links</li>
</ul>
`;
const navBar = document.createElement(\'nav\');
navBar.innerHTML = navLinks;
const appLayout = document.querySelector(\'app-layout\'); // works with \'body\' but not with \'appLayout\'
console.log(appLayout); // Logs correct element
appLayout.appendChild(navBar);
我知道我在这里尝试做的事情(在 Web 组件中加载脚本)并不理想,但是,我仍然想了解为什么上述方法不起作用。
-
使用编辑器中的 [<>] 按钮,使您的代码成为可执行的 SO sn-p;我们不会手动复制/粘贴您的代码。
标签: javascript dom web-component native-web-component