我正在尝试根据这些设置生成表单...
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
})
}
}
答案 0 :(得分:3)
除了将变量作为模板文字使用之外,您还可以动态创建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;
});
}
};