能否为HTML链接赋值以追踪问卷选择并实现院校推荐?
纯HTML能否追踪答题选项实现院校推荐?
核心结论
纯HTML做不到追踪用户选择并计算推荐结果——HTML只是静态标记语言,只能展示内容,没有数据存储、逻辑计算的能力,必须结合JavaScript来完成需求。
适合初学者的两种实现方案
方案1:用LocalStorage存储选择记录(推荐)
这种方法会把用户的每一次选择存在浏览器本地,最后一页直接读取统计,操作简单且不会轻易丢失数据(除非用户手动清理浏览器缓存)。
- 修改每个问题页面的代码,给选项链接添加点击事件来存储选择类型:
<title>Question 13</title> <script> // 存储选择的函数 function saveChoice(type) { // 先读取已有的选择记录,没有就初始化空数组 let choices = JSON.parse(localStorage.getItem('collegeChoices')) || []; // 把当前选择加入数组 choices.push(type); // 存回浏览器本地 localStorage.setItem('collegeChoices', JSON.stringify(choices)); } </script> </head> <body style="background-color:white;"> <h1 style="font-family:fantasy;text-align:center;color:black;font-size:100px;"> Does the number of enrolled students matter to you? </h1> <p style="font-family:monaco;text-align : center;color:black;font-size:30px;"> <br> <br> <a href="prestige10.html" onclick="saveChoice('prestige')"> I care about a small undergraduate enrollment size. </a> <br> <br> <a href="middle10.html" onclick="saveChoice('middle')"> The more the merrier. </a> <br> <br> <a href="college10.html" onclick="saveChoice('college')"> It does not matter to me. </a> </p>
所有问题页面都按这个格式修改,把saveChoice的参数对应改成prestige/middle/college即可。
- 制作结果页,读取存储的选择并计算推荐:
<title>推荐结果</title> <script> window.onload = function() { // 读取所有选择记录 let choices = JSON.parse(localStorage.getItem('collegeChoices')) || []; // 统计各类选择的数量 let prestigeCount = choices.filter(item => item === 'prestige').length; let middleCount = choices.filter(item => item === 'middle').length; let collegeCount = choices.filter(item => item === 'college').length; // 判断推荐结果 let resultText = ''; if (prestigeCount >= middleCount && prestigeCount >= collegeCount) { resultText = '推荐你申请常春藤院校!'; } else if (middleCount >= prestigeCount && middleCount >= collegeCount) { resultText = '推荐你申请普通院校!'; } else { resultText = '推荐你申请社区院校!'; } // 把结果显示在页面上 document.getElementById('result').innerText = resultText; // 可选:清空存储,方便下次测试答题 localStorage.removeItem('collegeChoices'); } </script> </head> <body style="background-color:white;"> <h1 style="font-family:fantasy;text-align:center;color:black;font-size:100px;">你的院校推荐</h1> <p id="result" style="font-family:monaco;text-align : center;color:black;font-size:30px;"></p> </body>
方案2:用URL参数传递选择(无需存储)
这种方法不需要存数据,每一页跳转时把选择拼在URL后面,最后一页读取所有参数统计。
比如修改问题页面的链接:
<a href="prestige10.html?choice=prestige"> I care about a small undergraduate enrollment size. </a> <a href="middle10.html?choice=middle"> The more the merrier. </a> <a href="college10.html?choice=college"> It does not matter to me. </a>
然后每一页都要把上一页的choice参数继续拼到下一页的链接里(比如prestige10.html里的链接要写成next.html?choice=prestige,多次选择就累加参数如next.html?choice=prestige&choice=middle),最后结果页用JS读取URL里的所有choice参数统计数量。
这种方法缺点是URL会越来越长,且用户刷新页面可能丢失之前的参数,不如LocalStorage方便。
内容的提问来源于stack exchange,提问作者Jacob Long
相关产品推荐
相关产品推荐

