【问题标题】:setAttribute in change event listener does not update the view更改事件侦听器中的 setAttribute 不更新视图
【发布时间】: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


【解决方案1】:

您可能想要inputkeyup 事件。

上的change 事件仅在按下 Enter 键或字段失去焦点时触发

来源:Change Event:

另请注意:您的data-source,因为data- 前缀成为数据属性

所以this.getAttribute("data-source")可以写成:this.dataset.source

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

【讨论】:

  • 我同意这可能更适合这个用例。我仍然不明白为什么 setAttribute("value",..) 不足以更新视图,即使 firstTerm 和 event.target 引用相同的 HTML 元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多