javascript - 问卷的正确数据结构是什么

标签 javascript jquery json user-interface data-structures

我正在尝试开发一份调查问卷,其中问题取决于答案,
保存问题和调查问卷流程的正确 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 ________

最佳答案

假设我们只有以下约束:

  • 您希望每个问题只定义一次
  • 问题可以取决于之前提出的任何问题的任何答案

然后我提出以下通用解决方案:

// 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);

您可能希望为每个问题添加更多详细信息,例如验证函数、类型( bool 值、文本、选择等)等。

如果您需要以纯 JSON 形式存储和传输问题,则需要将条件函数替换为诸如 conditions: [{id: "code-java", operator: "equals"之类的数据结构,值:“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))

关于javascript - 问卷的正确数据结构是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397222/

相关文章:

javascript - 在第三方js代码中使用jquery

c# - ServiceStack Json反序列化错误

java - 使用 Jackson 反序列化为 Map<String, String>

iOS 构建成功但归档失败

javascript - 通过nodejs gm库中的URL加载字体

javascript - 按日期 react 排序

Javascript:从iframe调用父函数

javascript - 为什么 moment.js 对待破折号和斜杠的方式不同?

javascript - jquery 3.1.0 如何触发回调

javascript - 遍历 if,如果为 false 则返回,如果为 true => 停止 if