我正在尝试根据这些设置生成表格...
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
})
}
}
除了将变量用作模板文字之外,您还可以动态创建HTML输入元素并将事件附加到该元素上,也可以仅将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;
});
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句