【发布时间】:2020-06-12 21:56:34
【问题描述】:
我正在尝试对在其自己的 Web 组件中构建的文本字段使用“默认”字符串。默认情况下,我定义了一个字符串,当文本字段被清空时,该字符串会被完全重新打印。输入元素引用上的 setAttribute 确实会更改文本字段值但不会更新视图。另一方面,通过事件的目标访问值会这样做,即使两者都引用相同的元素 - 至少据我所知。
在提供的 sn-p 中问题很明显。
提前致谢。
class editForm extends HTMLDivElement {
static get observedAttributes() {
return ["data-source"];
}
constructor() {
self = super();
let firstTerm = document.createElement("input");
firstTerm.setAttribute("type", "text");
firstTerm.setAttribute("class", "form-control mr-2");
firstTerm.setAttribute("aria-label", "Source Term");
firstTerm.setAttribute("value", this.getAttribute("data-source"));
firstTerm.addEventListener("change", (e) => {
let input = e.target.value;
if (input.trim() === "") {
//this line alone does not suffice to update the printed text field value
firstTerm.setAttribute("value", this.getAttribute("data-source"));
input = this.getAttribute("data-source");
//commenting out the following line results in the data-source string
//not being reprinted within the text field
e.target.value = input;
}
});
self.appendChild(firstTerm);
}
}
customElements.define("edit-form", editForm, {
extends: "div",
});
<div is='edit-form' data-source='test'></div>
【问题讨论】:
-
请注意,Safari 不支持
extends: "div"(自定义内置元素),Apple 仍然拒绝实现它们。
标签: javascript html dom web-component event-listener