我想创建一个Web组件,其中包含可以添加到其中的元素的列表。例如,如果我有一个初始模板,例如:
const template = document.createElement("template");
template.innerHTML = `<input type="text"></input><button>add div</button>`;
class MyElement extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({ mode: "open" });
this._shadowRoot.appendChild(template.content.cloneNode(true));
const button = this._shadowRoot.querySelector("button");
button.addEventListener("click", this.addDiv);
}
addDiv(e) {
// ...
}
}
customElements.define("my-element", MyElement);
每次单击该按钮时,<div>
都会添加一个包含来自输入字段的文本的,从而创建如下内容:
<input type="text"></input><button>add div</button>
<div>first text from input added</div>
<div>second text from input added</div>
...
在您的情况下,您不能insertAjacentHTML()
在Shadow DOMshadowRoot
属性上使用,因为Shadow Root无法实现Element接口。
更好的解决方案是appendChild(
在shadowRoot
属性上使用)。但是,您需要bind()
在click
事件回调上添加特殊操作。
在事件回调中,它确实引用了触发事件的元素,而不是在其中定义回调的对象。
为了获得对自定义元素的引用(为了访问Shadow DOM中的输入元素shadowRoot
,请调用bind(this)
inside addEventListener()
。
button.addEventListener( "click", this.addDiv.bind( this ) )
请参阅下面的完整示例:
const template = document.createElement("template");
template.innerHTML = `<input type="text"></input><button>add div</button>`;
class MyElement extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({ mode: "open" });
this._shadowRoot.appendChild(template.content.cloneNode(true));
const button = this._shadowRoot.querySelector("button");
button.addEventListener("click", this.addDiv.bind( this ) );
}
addDiv(e) {
var div = document.createElement( 'div' )
div.textContent = this.shadowRoot.querySelector( 'input' ).value
this.shadowRoot.appendChild( div )
}
}
customElements.define("my-element", MyElement);
<my-element></my-element>
另一个解决方案是使用箭头功能。使用箭头功能,此功能不会重新定义,因此您无需使用bind()
。
class MyElement extends HTMLElement {
constructor() {
super()
const sh = this.attachShadow( { mode: "open" } )
sh.innerHTML = `<input type="text"></input><button>add div</button>`
const button = sh.querySelector( "button" )
button.onclick = ev => {
let div = document.createElement( "div" )
div.textContent = sh.querySelector( "input" ).value
sh.appendChild( div )
}
}
}
customElements.define( "my-element", MyElement )
<my-element></my-element>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句