我正在尝试开发一个问卷依赖于答案的调查问卷。
什么是正确的UI数据结构来保存问题和问卷流?
很抱歉如果这个不清楚,想根据答案消除UI的某些部分,所以我需要在Java脚本中使用某种数据结构,这样我就可以根据答案动态修改html,所以问题是如何将数据作为json引入页面,以及如何在JS中保存它并根据json和答案消除UI的某些部分。
1 What is your name?_______
2 Did you ever code in java?___Y/N____
3 <Question should appear only if answer is yes> How many years? ____
4 <Question should appear only if answer is no> Did you ever code using any programming language? ____
5 Select occupation
a Developer
b Project manager
6 <Question should appear only if answer to 5 is b> years experience in project management ________
答案 0 :(得分:9)
我们说我们只有以下限制:
然后我提出以下通用解决方案:
// Each question has an id, a text and a condition depending on previous answers:
var questions = [
{id: "name", text: "What is your name?"},
{id: "code-java", text: "Did you ever code in Java?"},
{id: "code-java-years", text: "How many years?", condition: answers => answers["code-java"] == "yes"},
{id: "code-other", text: "Did you ever code using any programming language?", condition: answers => answers["code-java"] == "no"},
{id: "occupation", text: "Select occupation?"},
{id: "experience-management-years", text: "Years experience in project management?", condition: answers => answers["occupation"] == "Project manager"}
]
// Ask all questions whose conditions evaluate to true and collect the answers:
var answers = {};
questions.forEach(question => {
if (!question.condition || question.condition(answers)) {
answers[question.id] = prompt(question.text);
}
});
console.log(answers);
&#13;
您可能希望为每个问题添加更多详细信息,例如验证函数,类型(布尔值,文本,选择等)等。
如果您需要以普通JSON格式存储和转移问题,则需要将条件函数替换为conditions: [{id: "code-java", operator: "equals", value: "yes"}]
等数据结构,该数据结构由
operators = {
'equals': (answer, value) => answer == value,
'regex': (answer, value) => new RegExp(value).test(answer),
...
}
conditions.every(condition => operators[condition.operator](answers[condition.id], condition.value))