无法从DOM获取输入值:ReferenceError: inputEmail未定义问题
问题:DOM获取输入框值触发ReferenceError错误
报错信息
error caught ReferenceError: inputEmail is not defined at HTMLButtonElement.butn (
我的JS代码
class Formapp { constructor(fullname, email, job) { this.inputName = document.querySelector("#inputName"); this.inputEmail = document.querySelector("#Email"); this.inputJob = document.querySelector("#Job"); this.tbody = document.querySelector("#tbody"); this.btn = document.querySelector("#btn"); this.data = [] this.fullname = fullName this.email = email this.job = job } butn() { this.fullname = +inputName.value; this.email = +inputEmail.value; this.job = +inputJob.value this.data.push(fullName, email, job) console.log(this.data); console.log(this.inputEmail); this.tbody.innerHTML = this.data?.map(function(item, index) { return ` <tr class="table-light "> <td class="table-light">${index+1}${item.fullName}</td> <td class="table-light">${item.email}</td> <td class="table-light">${item.job}</td> </tr> ` }).join("") this.inputName.value = "" this.inputEmail.value = "" this.inputJob.value = "" } } var person1 = new Formapp("salam", 'k@k.com', 'asdasd') btn.onclick = person1.butn
问题描述
HTML部分无异常,类内部操作DOM时遇到问题。此前用构造函数实现同类功能完全正常,在butn()方法前调用console.log(this.inputEmail)能正常输出元素,但在butn方法内部却无法调用它。
解决方法
1. 修复this指向问题
当把person1.butn直接赋值给btn.onclick时,方法执行时的this会指向触发点击的按钮元素,而非person1实例。需要绑定正确的this:
// 替换原绑定代码的二选一方式 btn.onclick = person1.butn.bind(person1); // 或者 btn.onclick = () => person1.butn();
2. 修正变量引用与逻辑错误
- 类实例的属性必须通过
this.访问,比如inputName要改为this.inputName,否则会视为全局变量导致未定义错误 - 构造函数参数是
fullname(小写n),代码里误写成fullName(大写N),需统一拼写 - 输入值不需要用
+转换(姓名、邮箱都是字符串类型) - 往
data数组中要推送对象,而非单独变量,否则map时无法读取item.fullName这类属性
修复后的完整代码
class Formapp { constructor(fullname, email, job) { this.inputName = document.querySelector("#inputName"); this.inputEmail = document.querySelector("#Email"); this.inputJob = document.querySelector("#Job"); this.tbody = document.querySelector("#tbody"); this.btn = document.querySelector("#btn"); this.data = []; this.fullname = fullname; this.email = email; this.job = job; } butn() { // 读取输入值并赋值给局部变量 const fullname = this.inputName.value; const email = this.inputEmail.value; const job = this.inputJob.value; // 推送对象到数据数组 this.data.push({ fullname, email, job }); console.log(this.data); console.log(this.inputEmail); // 渲染表格行,使用正确的对象属性名 this.tbody.innerHTML = this.data.map(function(item, index) { return ` <tr class="table-light"> <td class="table-light">${index+1}. ${item.fullname}</td> <td class="table-light">${item.email}</td> <td class="table-light">${item.job}</td> </tr> `; }).join(""); // 清空输入框 this.inputName.value = ""; this.inputEmail.value = ""; this.inputJob.value = ""; } } var person1 = new Formapp("salam", 'k@k.com', 'asdasd'); // 绑定正确的this指向 btn.onclick = person1.butn.bind(person1);
内容的提问来源于stack exchange,提问作者Kanan Samandarli
相关产品推荐
相关产品推荐

