我希望下面的代码创建一个包含 div
的元素,其中包含文本“Hi”。
该元素出现在检查器中,但屏幕上看不到任何文本。
当我将模板从 template
更改为 div
时,文本会显示出来。我在这里做错了什么?
class MyComponent extends HTMLElement {
constructor() {
super()
const shadowRoot = this.attachShadow({ mode: 'open' })
const template = document.createElement('template')
const div = document.createElement('div')
div.innerHTML = 'Hi'
template.appendChild(div)
shadowRoot.appendChild(template.content)
}
}
customElements.define('my-component', MyComponent)
最佳答案
<template>
是一种特殊的元素。
通过其 content
添加一些 HTML 元素属性:
template.content.appendChild(div)
或通过其 innerHTML
添加 HTML 代码属性:
template.innerHTML = '<div>Hi</div>'
关于javascript - 使用 JS 创建的模板标记在附加到 Web 组件内的阴影时不会出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54169529/