QuerySelector在获取模板WebComponents后不起作用



TeleMenu有两个按钮,我试图抓住它们,但是this.shadowRoot.querySelector有一个问题。

错误:

Uncaught (in promise) TypeError: Cannot read property 'querySelector' of null

代码:

class TeleMenu extends HTMLElement {
buttons = [];
constructor() {
super();
fetch('tele-menu.html')
.then(resp => resp.text())
.then(resp => {
this.attachShadow({ mode: 'open' })
.innerHTML = resp
})
this.buttons = Array.from(this.shadowRoot.querySelectorAll('button'));
}

你能帮忙吗?

感谢

fetch是异步的,您正在执行.querySelectorAlllongbefore设置innerHTML

constructor() {
super();
fetch('tele-menu.html')
.then(resp => resp.text())
.then(resp => {
this.attachShadow({ mode: 'open' })
.innerHTML = resp
})
this.buttons = Array.from(this.shadowRoot.querySelectorAll('button'));
}

Google和MDN文档是错误的先运行super()

super()set andcreate'this'作用域。

所以你不能在super运行之前调用this。这是唯一的限制

你可以这样做:

constructor() {
fetch('tele-menu.html')
.then(resp => resp.text())
.then(resp => {
super().attachShadow({ mode: 'open' })
.innerHTML = resp;
this.buttons = [...this.shadowRoot.querySelectorAll('button')];//modern way
// do more here
})
}

https://javascript.info/async-await可能有助于保持您的代码更干净

最新更新