gpt4 book ai didi

javascript - 在 web component 中动态添加元素

转载 作者:行者123 更新时间:2023-12-03 07:04:18 29 4
gpt4 key购买 nike

我想创建一个 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>
...

最佳答案

在您的情况下,您不能在 Shadow DOM shadowRoot 属性上使用 insertAjacentHTML(),因为 Shadow Root 未实现 Element 接口(interface)。

使用绑定(bind)(this)

更好的解决方案是在 shadowRoot 属性上使用 appendChild()。但是,您需要添加一个特殊的 bind() click 事件回调的操作。

在事件回调中,this 确实引用了触发事件的元素,而不是定义回调的对象。

为了获取对自定义元素的引用(为了访问 Shadow DOM shadowRoot 中的 input 元素,在 中调用 bind(this) 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>


使用箭头函数

另一种解决方案是使用 arrow function .使用箭头函数,this 不会重新定义,因此您不需要使用 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>

关于javascript - 在 web component 中动态添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59347956/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com