
本文介绍如何使用 javascript 动态渲染问卷题目及对应选项,摆脱硬编码选项数量的限制,通过遍历 `questions[count].option` 数组灵活生成 `
在构建网页问卷时,若每个问题的选项数量不固定(例如有的题有 2 个选项,有的有 5 个),硬编码
首先确保你的问卷数据结构合理,例如:
const questions = [ { question: "你最喜欢的颜色?", options: ["红色", "蓝色", "绿色"] }, { question: "编程语言偏好?", options: ["javaScript", "python", "Rust", "go", "typescript"] } ];
接着,在渲染当前题目时,不再解构固定数量的变量,而是直接遍历 questions[count].options(注意:原答案中误写为 questions[count].question,应为 .options):
const q = questions[count]; let html = `Q${count + 1}. ${q.question}
`; for (const option of q.options) { html += `- ${option}
`; } html += '
'; question.innerHTML = html;
✅ 关键修正与优化说明:
- ✅ 循环对象必须是 q.options(选项数组),而非 q.question(题目字符串);
- ✅ 使用 for…of 更语义清晰,也可替换为 q.options.map(…).join(”) 实现函数式写法:
const optionsHtml = q.options .map((opt, idx) => `${opt} `) .join(''); question.innerHTML = ` Q${count + 1}. ${q.question}
${optionsHtml}
`;
? 进阶建议:
- 为每个
- 添加 data-index 属性,便于后续绑定点击事件并获取用户选择;
- 使用 textContent 替代模板字符串插值可防范 xss(若选项内容来自不可信来源);
- 考虑封装为独立函数,提升复用性:
function renderQuestion(container, questionObj, index) { const optionsHtml = questionObj.options .map((opt, i) => `${opt} `) .join(''); container.innerHTML = ` Q${index + 1}. ${questionObj.question}
${optionsHtml}
`; }
这样,无论每道题配置多少个选项,代码均能自动适配——真正实现「一次编写,多场景复用」。