表单多文本输入生成指定句子的JavaScript实现问题(禁用onclick)
问题分析与修正方案
原代码的核心问题
- 构造函数未将传入的参数保存为实例属性,导致
speak方法无法访问这些变量 - 模板字符串误用单引号(需用反引号
`),变量无法被解析;同时写错了参数名(需求里的class对应代码里的course),还多了不必要的+号 - 未给按钮绑定事件,也没有编写获取输入值、生成句子并输出到页面的逻辑
修正后的完整代码
<!DOCTYPE html> <html> <head> </head> <body> <a>Enter First Name</a> <br> <input type="text" id="firstName"></input> <br> <a>Enter Last Name</a> <br> <input type="text" id="lastName"></input> <br> <a>Enter Your Course</a> <br> <input type="text" id="course"></input> <br> <a>Enter Your Section</a> <br> <input type="text" id="section"></input> <br> <a>Enter Your Role</a> <br> <input type="text" id="role"></input> <p id="nameOutput"></p> <br> <input type="button" id="btn" value="Submit"> <script> // 修正构造函数,将参数保存为实例属性 function Sentence(firstName, lastName, course, section, role){ this.firstName = firstName; this.lastName = lastName; this.course = course; this.section = section; this.role = role; } // 修正模板字符串,使用反引号,替换正确变量名 Sentence.prototype.speak = function(){ return `${this.firstName} ${this.lastName} has the role of ${this.role} in ${this.course} section ${this.section}`; } // 用addEventListener绑定事件,避免使用onclick document.getElementById('btn').addEventListener('click', function() { // 获取所有输入框的值 const firstName = document.getElementById('firstName').value; const lastName = document.getElementById('lastName').value; const course = document.getElementById('course').value; const section = document.getElementById('section').value; const role = document.getElementById('role').value; // 实例化类并生成句子 const userSentence = new Sentence(firstName, lastName, course, section, role); const result = userSentence.speak(); // 将结果输出到页面 document.getElementById('nameOutput').textContent = result; // 同时打印到控制台 console.log(result); }); </script> </body> </html>
关键修正说明
- 构造函数修正:把传入的每个参数都赋值给
this对应的属性,这样实例才能在speak方法中访问这些值 - 模板字符串修正:改用反引号包裹,使用
this.xxx访问实例属性,同时把错误的${class}改成${this.course},去掉多余的+号,完全匹配需求的句子格式 - 事件绑定:使用
addEventListener给按钮绑定点击事件,完全避免了onclick属性,符合要求;在事件处理函数里完成输入值获取、类实例化、句子生成和页面输出的完整逻辑
内容的提问来源于stack exchange,提问作者Laura Henderson
相关产品推荐
相关产品推荐

