【问题标题】:Cannot appendChild to a custom web component无法将Child 附加到自定义 Web 组件
【发布时间】: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


【解决方案1】:

使用innerHTML 或在您的情况下使用insertAdjacentHTML&lt;script&gt; 标签添加到文档中不起作用,因为浏览器历来试图防止潜在的跨站点脚本攻击(https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0) 你可以做的是这样的:

const s = document.createElement("script");
s.type = "module";
s.innerText = `import './components/nav-bar.js'`;
this.append(s);
// or simply directly without the script: `import('./comp..')` if it is really your only js in the script tag.

【讨论】:

    猜你喜欢
    • 2022-07-06
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多