Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在使用include HTML后查询元素(window.customElements.define()_Javascript_Html_Dom - Fatal编程技术网

Javascript 如何在使用include HTML后查询元素(window.customElements.define()

Javascript 如何在使用include HTML后查询元素(window.customElements.define(),javascript,html,dom,Javascript,Html,Dom,customElements.define()使组件用于包含来自其他文件的一些HTML。它工作正常,但我无法查询元素,因为当我查询该元素时,它不会出现(我认为它正在加载)。如何修复它 index.html正文 <body> <my-component src="navbar.html"></my-component> <my-component src="contact-us.html">&l

customElements.define()使组件用于包含来自其他文件的一些HTML。它工作正常,但我无法查询元素,因为当我查询该元素时,它不会出现(我认为它正在加载)。如何修复它

index.html正文

<body>
    <my-component src="navbar.html"></my-component>
    <my-component src="contact-us.html"></my-component>
    <my-component src="footer.html"></my-component>
<script>
    class HTMLInclude extends HTMLElement {
        constructor() {
            super();
            this.innerHTML = "Loading...";
            this.loadContent();
        }

        async loadContent() {
            const source = this.getAttribute("src");
            if (!source) {
                throw new Error("No src attribute given.");
            }
            const response = await fetch(source);
            if (response.status !== 200) {
                throw new Error(`Could not load resource: ${source}`);
            }
            const content = await response.text();
            this.innerHTML = content;
        }
    }

    window.customElements.define("my-component", HTMLInclude);
    
    //text will be null because it cannot query in this time
    let text = document.querySelector("#textBox");
    console.log(text);
    // null 
</script>
</body>

类HTMLInclude扩展HTMLElement{
构造函数(){
超级();
this.innerHTML=“正在加载…”;
这是loadContent();
}
异步加载内容(){
const source=this.getAttribute(“src”);
如果(!源){
抛出新错误(“未给出src属性”);
}
const response=等待获取(源);
如果(response.status!==200){
抛出新错误(`无法加载资源:${source}`);
}
const content=wait response.text();
this.innerHTML=内容;
}
}
定义(“我的组件”,HTMLInclude);
//文本将为空,因为此时无法查询
让text=document.querySelector(“#textBox”);
console.log(文本);
//空的
contact-us.html

<div id="textBox">
    <p>Lorem sium....</p>
</div>

罗勒姆·斯尤姆

CSS可以应用于contact-us.html中的元素,但目前无法在DOM中查询元素并导入文件html