【发布时间】:2020-04-24 11:41:38
【问题描述】:
在我的以下代码中,值的更改不会更新输入值:为什么?
class textfield extends HTMLElement {
get value()
{
return this.getAttribute("value");
}
set value(val)
{
this.setAttribute('value', val);
}
get readonly() {
return this.hasAttribute("readonly");
}
set readonly(val)
{
if (val)
{
this.setAttribute("readonly", '');
}
else
{
this.removeAttribute("readonly");
}
}
static get observedAttributes() {
return ['readonly', 'value'];
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(name, newValue) ;
}
constructor()
{
super();
this.attachShadow({ "mode": "open" });
}
connectedCallback()
{
this.shadowRoot.innerHTML =
/*html*/`
<div>
<div>
Lable
</div>
<div>
<input id="vi-input" type="text" value="${this.getAttribute("value")}" ${ this.hasAttribute("readonly") ? "readonly" : "" } />
</div>
<div>
<span>Error</span>
</div>
</div>
`;
}
}
window.customElements.define("vi-textfield", textfield);
在我的 index.html 中:
....
<vi-textfield id="myInput" value="2" validation="^\d{4}$" ></vi-textfield>
....
当我通过 JS 更新它时,让我们说:
document.getElementById("myInput").value = 3;
会有attributeChangedCallback的给定console.log,但值本身不会改变......
【问题讨论】:
标签: javascript html web-component shadow-dom