使用 HTML + JavaScript 实现交互式决策问卷与结果导出教程

2次阅读

使用 HTML + JavaScript 实现交互式决策问卷与结果导出教程

本文详解如何用纯前端技术构建 20 题交互式问卷系统,通过 dom 动态渲染问题、收集用户选择,并在完成后生成可下载的个性化建议清单(.txt 文件),全程无需后端或 node.js fs 模块。

本文详解如何用纯前端技术构建 20 题交互式问卷系统,通过 dom 动态渲染问题、收集用户选择,并在完成后生成可下载的个性化建议清单(.txt 文件),全程无需后端或 node.js fs 模块。

在浏览器环境中,javaScript 无法直接访问本地文件系统(如 fs.writeFile),也不能指定保存路径——这是出于严格的安全沙箱限制。因此,原问题中依赖 Node.js 的 fs 模块、尝试在浏览器里写入磁盘文件的写法必然失败。但好消息是:完全可通过纯前端方案优雅实现目标——即动态呈现问题、构建决策逻辑、汇总答案,并触发用户可控的文件下载。

✅ 正确的技术路径

  1. html 结构负责容器与交互入口
    使用

    承载当前题目,

    <script> const questions = [ { text: "您是否愿意从事兼职工作?", key: "willing-part-time", options: ["是", "否"] }, { text: "您是否有闲置物品可出售?", key: "has-items-to-sell", options: ["是", "否"] }, { text: "您能否每月稳定储蓄500元以上?", key: "can-save-monthly", options: ["是", "否"] } // ……补全至20题(此处仅示意) ]; let currentIdx = 0; const responses = {}; const $container = document.getElementById("question-container"); const $nextBtn = document.getElementById("next-btn"); const $resultsSection = document.getElementById("results-section"); const $resultsOutput = document.getElementById("results-output"); const $downloadBtn = document.getElementById("download-btn"); function renderQuestion() { const q = questions[currentIdx]; $container.innerHTML = ` <h3>第${currentIdx + 1}题:${q.text} ${q.options.map((opt, i) => `<label><input type="radio" name="q${currentIdx}" value="${opt}"> ${opt}<br>` ).join(”)} `; } $nextBtn.addEventListener("click", () => { const selected = document.querySelector(`input[name="q${currentIdx}"]:checked`); if (!selected) return; responses[questions[currentIdx].key] = selected.value === "是"; if (currentIdx < questions.Length – 1) { currentIdx++; renderQuestion(); } else { // 所有问题结束,生成建议并显示结果区 const recs = []; if (responses["willing-part-time"]) recs.push("✅ 注册自由职业平台(如程序员客栈、圆领)"); if (responses["has-items-to-sell"]) recs.push("✅ 整理旧物,发起微信闲置群或闲鱼专场"); if (responses["can-save-monthly"]) recs.push("✅ 开通支付宝「笔笔攒」或银行智能定投"); $resultsOutput.textContent = recs.length ? recs.join("n") : "暂无匹配建议,请检查答案或拓展选项范围。"; $resultsSection.hidden = false; $container.hidden = true; $nextBtn.hidden = true; } }); $downloadBtn.addEventListener("click", () => { const blob = new Blob([$resultsOutput.textContent], { type: "text/plain;charset=utf-8" }); const url = URL.createObjectURL(blob); const a = Object.assign(document.createElement("a"), { href: url, download: "my-action-plan.txt" }); document.body.append(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }); renderQuestion(); // 初始化首题 </script>

text=ZqhQzanResources