JavaScript创建文本框输入型问卷报addEventListener错误求助
问卷功能修复方案
报错根因
你遇到的Uncaught TypeError: nextButton.addEventListener is not a function报错,核心是调用问卷初始化函数时参数顺序完全传错:
函数定义的参数顺序为(问题数组, 下一题按钮DOM元素, 问卷渲染容器DOM元素, 答题完成回调),但你调用时第二个参数传入了文本框的字符串值,字符串没有DOM事件监听方法,直接触发报错。
需要调整的核心逻辑
- 修正初始化函数的传参顺序,传入正确的DOM元素
- 适配文本输入答题逻辑,删除原单选按钮的多选项遍历代码,每道题仅生成1个文本输入框
- 修正答案校验规则,兼容数字、字符串的类型差异(比如用户输入
"42"和正确答案数字42判定为匹配) - 删除原单选按钮专属的
selectedAnswer相关逻辑,改为直接读取文本框的输入值做校验
完整修改后代码
JavaScript代码
const questions = [ { question: '你当前使用的是什么平台?', correctAnswer: 'Stackoverflow', points: 5 }, { question: '40 + 2等于多少?', correctAnswer: 42, points: 1 }, { question: '7*6等于多少?', correctAnswer: 42, points: 1 } ]; // 问题遍历生成器 function *questionsGenerator( questions ) { yield* questions; } const questionaire = ( query, nextButton, target, onCompleted ) => { let score = 0; let iterator = questionsGenerator( query ); let currentQuestion = null; let answerInput = null; // 存储当前题目的输入框DOM nextButton.addEventListener('click', nextQuestion); function evaluateAnswer() { if (!currentQuestion || !answerInput) return; const userInput = answerInput.value.trim(); // 兼容数字和字符串的类型差异 const isCorrect = String(userInput) === String(currentQuestion.correctAnswer); if (isCorrect) { score += currentQuestion.points; } } function nextQuestion() { evaluateAnswer(); const next = iterator.next(); if (next.done) { nextButton.removeEventListener('click', nextQuestion); onCompleted( score ); return; } currentQuestion = next.value; drawUI(); } function drawUI() { // 禁用下一题按钮,直到用户输入内容 nextButton.setAttribute('disabled', true); // 清空之前的内容 Array.from( target.childNodes ).forEach( child => target.removeChild( child ) ); // 渲染题目 const title = document.createElement('h1'); title.innerHTML = currentQuestion.question; target.appendChild( title ); // 渲染文本输入框 answerInput = document.createElement('input'); answerInput.type = 'text'; answerInput.placeholder = '请输入答案'; // 用户输入内容后解锁下一题按钮 answerInput.addEventListener('input', () => { if (answerInput.value.trim()) { nextButton.removeAttribute('disabled'); } else { nextButton.setAttribute('disabled', true); } }); target.appendChild(answerInput); // 自动聚焦输入框,优化体验 answerInput.focus(); } return { nextQuestion } }; // 初始化问卷,修正参数顺序 questionaire( questions, document.querySelector('#btnNext'), document.querySelector('#questionaire'), score => alert('你的最终得分是:' + score ) ).nextQuestion();
HTML代码
<h1>问卷</h1> <div id="questionaire"></div> <div class="toolstrip"> <button id="btnNext" type="button">下一题</button> </div>
注:原HTML中提前写的id为text的输入框已不需要,代码会根据题目动态生成输入框
内容的提问来源于stack exchange,提问作者stosto
相关产品推荐
相关产品推荐

