javascript - 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
})
}
}
解决方案
除了将变量作为模板文字之外,您还可以动态创建一个 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;
});
}
};
推荐阅读
- rust - rust const fn 究竟是什么意思
- python - 无效的语法错误(discord.py)如果你能修复它会很好
- javascript - 如何获取没有括号且没有换行符的数组元素?
- twilio - 只听驳船
- html - 如何为每张图片添加一个 url 链接?
- excel - 用 VBA excel 交换行
- python - 将 .py 转换为 .exe 后,Selenium webdriver 无法正常工作
- excel - 将字符串保存到 VBA 中未初始化的 Variant 变量中
- google-chrome-extension - 单击按钮时打开从 popup.html 打开的相同窗口
- firebase - 无法从方法“_userFromFirebaseUser”返回“用户”类型的值