You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现文本框输入型问卷的运行错误修复求助

问卷功能修复方案

存在的问题

  • 函数传参顺序错误,定义的参数顺序和调用时传入的参数顺序不匹配
  • 答案判断逻辑错误:questions数组中正确答案字段为answers,但判断时用了不存在的correct字段;且原有逻辑是为单选设计的,不符合文本输入验证的需求
  • DOM操作逻辑错误:question.answers是单个值(字符串/数字),不能调用map方法遍历
  • 选择器语法错误:document.querySelector('input'[id="text"])引号位置错误,且误将输入框的值作为按钮参数传入
  • 输入值获取逻辑错误:原有selectedAnswer存储的是索引值,未实际获取用户输入的文本内容

修复后的完整代码

JS代码

const questions = [
  { 
    question: '你当前使用的平台是什么?',
    answers: 'Stackoverflow',
    points: 5
  },
  { 
    question: '40 + 2等于多少?',
    answers: 42,
    points: 1
  },
  { 
    question: '7乘以6等于多少?',
    answers: 42,
    points: 1
  }
];

function *questionsGenerator( questions ) {
  yield* questions;
}

const questionaire = ( query, nextButton, answerInput, target, onCompleted ) => {
  let score = 0;
  let iterator = questionsGenerator( query );
  let question = null;
  let userInput = '';

  nextButton.addEventListener('click', nextQuestion);
  answerInput.addEventListener('input', () => {
    userInput = answerInput.value.trim();
    // 输入不为空时才允许点击下一题
    userInput ? nextButton.removeAttribute('disabled') : nextButton.setAttribute('disabled', true);
  });
  
  function evaluateAnswer() {
    if (!question || !userInput) return;
    // 统一转成字符串比较,兼容数字和字符串答案
    if (String(question.answers) === String(userInput)) {
      score += question.points;
    }
    // 清空输入框
    answerInput.value = '';
    userInput = '';
  }
  
  function nextQuestion() {
    evaluateAnswer();
    question = iterator.next();
    if (question.done) {
      nextButton.removeEventListener('click', nextQuestion);
      answerInput.remove();
      nextButton.remove();
      onCompleted( score );
      return;
    }
    question = question.value;
    drawUI();
  }
  
  function drawUI() {
    nextButton.setAttribute('disabled', true);
    Array.from( target.childNodes ).forEach( child => target.removeChild( child ) );
    const title = document.createElement('h2');
    title.innerHTML = question.question;
    target.appendChild( title );
  }
  
  return {
    nextQuestion
  }
};

// 初始化问卷
questionaire(
  questions, 
  document.querySelector('#btnNext'), 
  document.querySelector('#text'),
  document.querySelector('#questionaire'), 
  score => alert('你的得分是: ' + score ) 
).nextQuestion();

HTML代码

<h1>调查问卷</h1>
<div id="questionaire"></div>
<input type="text" id="text" placeholder="请输入答案"/>
<div class="toolstrip">
  <button id="btnNext" type="button" disabled>下一题</button>
</div>

内容的提问来源于stack exchange,提问作者PitxRosalina Pitalina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:54:07