首页 > 解决方案 > addEventListener 在函数内部不起作用

问题描述

我正在尝试根据这些设置生成表单...

let formItems = new Form("form-items", {
        items: [
            { id: "companyName" },
            { id: "documentKey" },
            { id: "documentDate" }
        ],
    });

在里面,我生成每个输入,并尝试添加一个eventListener,但它不起作用。我究竟做错了什么?

module.exports = function Form(formElementId, options) {

    this.state = {}

    options.items.map(item => {
        renderInput(item.id);
        this.state[item.id] = ""
    })

    function renderInput(id) {

        let html = `<input id="${id}" />`

        document.getElementById(formElementId).innerHTML += html;

        document.getElementById(id).addEventListener("input", (e) => {
            console.log(e);                      // <--------- Doesn't work
            this.state[id] = e.target.value;     // <--------- Doesn't work
            console.log(this.state);             // <--------- Doesn't work
        })
    }
}

标签: javascriptdomaddeventlistener

解决方案


除了将变量作为模板文字之外,您还可以动态创建一个 HTML 输入元素并将事件附加到它,而不是将 HTML 添加到使用+=刚刚附加到容器中

我会改用这个片段:

module.exports = function Form(formElementId, options) {
  this.state = {};
  self = this;
  options.items.map(item => {
    renderInput(item.id);
    this.state[item.id] = "";
  });

  function renderInput(id) {
    let input = document.createElement("input");
    input.setAttribute("id", id);

    document.getElementById(formElementId).append(input);

    input.addEventListener("input", e => {
      self.state[id] = e.target.value;
    });
  }
};

推荐阅读