我尝试通过 Web 组件创建自定义文本框
'use strict';
class TextBox extends HTMLElement {
constructor() {
super();
var shadow = this.attachShadow({ mode: 'open' });
let textbox = document.createElement("input");
shadow.appendChild(textbox);
textbox.addEventListener("change", this.validate);
textbox.value ="Init";
}
validate(event) {
console.log("input can be validated");
}
get value() {
console.log("get");
let textbox = this.shadowRoot.querySelector("input");
return textbox.value;
}
set value(newValue) {
console.log("set");
let textbox = this.shadowRoot.querySelector("input");
textbox.value = newValue;
}
}
customElements.define('test-textbox',TextBox);
稍后我想将自定义输入嵌入模板并在添加之前更改其值:
let control= document.getElementById("control");
let clone = control.content.cloneNode(true);
clone.children[0].value = "tb value has been changed before adding";
document.getElementById("app").appendChild(clone);
但是如果在我的代码中执行此操作,则输入的值将保持在“Init”上,但我的自定义控件的值将具有属性“tb value has been changed before adding”。
从 HTMLInput 扩展会更好吗?设置的例程也只触发一次。