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

求助:如何为allQuestions数组的answers元素添加单选按钮

嘿,我看你遇到的问题是想给每个问题的答案选项加上单选按钮,但只针对allQuestions[index].answers里的元素对吧?先给你提个小细节:你代码里的anwsers拼写错啦,应该是answers,这个小错误可能也会影响后续逻辑哦~

下面分两种常见场景给你解决方案:

原生JavaScript实现方案

如果是在普通HTML页面里开发,我们可以通过动态创建DOM元素来实现需求:

  1. 先准备一个HTML容器用来渲染内容:
<div id="quiz-container"></div>
  1. 再编写JS逻辑遍历数组,逐个渲染问题和对应的单选按钮:
const allQuestions = [
  { 
    question: "Which of them is from compton", 
    answers: ["Nas", "Tupac", "Omarion", "Kendrick"], // 修正拼写为answers
    correctAnswer: "Kendrick" 
  },
  { 
    question: "founder of HipHop", 
    answers: ["Tupac", "Eazy E", "Kendrick", "Bambata"], // 修正拼写
    correctAnswer: "Bambata" 
  }
];

const quizContainer = document.getElementById('quiz-container');

allQuestions.forEach((questionObj, index) => {
  // 创建问题标题
  const questionTitle = document.createElement('h3');
  questionTitle.textContent = `${index + 1}. ${questionObj.question}`;
  quizContainer.appendChild(questionTitle);

  // 创建选项分组容器
  const optionsWrap = document.createElement('div');
  
  questionObj.answers.forEach(answer => {
    // 创建单选按钮的标签容器
    const optionItem = document.createElement('label');
    
    // 创建单选按钮核心元素
    const radioBtn = document.createElement('input');
    radioBtn.type = 'radio';
    radioBtn.name = `question-${index}`; // 同一问题的单选按钮name必须一致,才能实现单选组
    radioBtn.value = answer;

    // 添加答案文本
    const answerText = document.createTextNode(` ${answer}`);

    // 组装元素并添加到容器
    optionItem.appendChild(radioBtn);
    optionItem.appendChild(answerText);
    optionsWrap.appendChild(optionItem);
  });

  quizContainer.appendChild(optionsWrap);
});

这里的核心是同一个问题下的所有单选按钮要设置相同的name属性,这样浏览器才会把它们识别为一组,保证只能选中一个选项。


React框架下的实现方案

如果是用React开发,代码会更简洁直观:

import React from 'react';

const allQuestions = [
  { 
    question: "Which of them is from compton", 
    answers: ["Nas", "Tupac", "Omarion", "Kendrick"],
    correctAnswer: "Kendrick" 
  },
  { 
    question: "founder of HipHop", 
    answers: ["Tupac", "Eazy E", "Kendrick", "Bambata"],
    correctAnswer: "Bambata" 
  }
];

function QuizComponent() {
  return (
    <div className="quiz-wrap">
      {allQuestions.map((question, qIndex) => (
        <div key={qIndex} className="question-card">
          <h3>{qIndex + 1}. {question.question}</h3>
          <div className="options-group">
            {question.answers.map((answer, aIndex) => (
              <label key={aIndex} className="option-item">
                <input
                  type="radio"
                  name={`question-${qIndex}`}
                  value={answer}
                />
                {answer}
              </label>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

export default QuizComponent;

如果你之前的代码没生效,大概率是两个原因:

  • 拼写错误:把answers写成了anwsers,导致遍历不到正确的答案数组
  • 单选按钮的name没有按问题分组,导致所有按钮都在同一组,或者组名不匹配

你可以先检查这两点,再试试上面的代码~

内容的提问来源于stack exchange,提问作者Kondas Lamar Jnr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:17:42