我正在尝试在 Web 组件模板中的两个插槽中添加 onclick 事件。我尝试用一个跨度包围它,然后运行
.querySelector
来获取该跨度,但它没有找到 #label-wrapper
元素 - 我很困惑。
HTML:
<template><span id="label-wrapper"><slot></slot>: <slot name="number"></slot></span></template>
Javascript
constructor(tab) {
super();
let template = document.getElementById("example-template");
let templateContent = template.content;
const containerNode = (templateContent.cloneNode(true));
this.tab = tab;
let slotNode = containerNode.querySelector("slot")
slotNode.append("Example label");
let labelWrapper = containerNode.querySelector("#label-wrapper");
labelWrapper.onclick = () => {
// Do something
}
this.append(containerNode);
在处理 Web 组件和影子 DOM 时,由于影子 DOM 封装其内容的方式,模板或影子根中的元素有时会更难以交互。在您的情况下,问题似乎源于尝试查询文档片段中尚未附加到影子 DOM 或被错误引用的元素。
确保模板已附加到影子 DOM,在查询模板内的元素之前,您需要确保模板内容已附加到自定义元素的影子 DOM。
在shadow DOM内部查询,一旦模板内容是shadow root的一部分,您应该查询此根内的元素,而不是直接查询文档片段。
方法:
constructor(tab) {
super();
this.attachShadow({mode: 'open'}); // Ensure you have a shadow root created
let template = document.getElementById("example-template");
let templateContent = template.content.cloneNode(true);
this.shadowRoot.appendChild(templateContent); // Attach the template content to the shadow root
let labelWrapper = this.shadowRoot.querySelector("#label-wrapper"); // Query within the shadow root
labelWrapper.onclick = () => {
// Do something
};
}
确保您的 HTML 模板元素
(<template id="example-template">...</template>)
在自定义元素尝试访问它之前已正确定义并在 DOM 中可用。这通常意味着在 HTML 中声明您的模板或在处理自定义元素的定义或实例之前动态确保其可用。