【问题标题】:How to make form code efficient and not redundant如何使表单代码高效而不冗余
【发布时间】:2014-11-22 13:44:15
【问题描述】:

我正在制作一个自定义提问器,它将向用户询问一组是和否的问题。当用户回答这些问题时,它将对最终组合的可能性进行分类。我正在尝试找到一种更简单的方法来明智地完成此代码。

这是我的 jsfiddle,可以更轻松地解释它。请记住,我知道我的方法是多余的。 http://jsfiddle.net/tLaefycp/

<div id="Q1">
    <input type="radio">Yes
    <input type="radio">No
</div>

    <div id="Q2"> <!-- Yes to q1 -->
        <input type="radio">Yes
        <input type="radio">No
    </div>

    <div id="Q2"> <!-- No to Q1 -->
        <input type="radio">Yes
        <input type="radio">No
    </div>

        <div id="Q3"> <!-- Yes to q1 and q2 -->
            <input type="radio">Yes
            <input type="radio">No
        </div>

        <div id="Q3"> <!-- yes to q1 no to q2 -->
            <input type="radio">Yes
            <input type="radio">No
        </div>

        <div id="Q3"> <!-- no to q1 yes to q2 -->
            <input type="radio">Yes
            <input type="radio">No
        </div>

        <div id="Q3"> <!-- no to q1 no to q2 -->
            <input type="radio">Yes
            <input type="radio">No
        </div>

【问题讨论】:

  • ids 必须是唯一的!!

标签: jquery html forms conditional conditional-statements


【解决方案1】:

以编程方式创建问题和答案,直接使用带有已定义值数组的 jquery,而不是从一开始就将其全部保存在 html 中。我为您提供了一个简化的示例结构,您需要弄清楚逻辑。但它应该给你一个起点。

如果您迭代一般问题,然后在得到答案后,从 data 对象中迭代适当的数组,您可以简化代码。例如,用户选择trucks,那么我们知道我们必须遍历truckQuestions

var data = {genericQuestions : 
                [{question:"Do you like cars or trucks?",
                  answers: [["cars","carQuestions"],
                            ["trucks","truckQuestions"]]
                 }],
            truckQuestions :
                [{question:"Do you want a lift on your truck?",
                  answers: ["Yes","no"]
                  }
                 //More questions
                 ],
            carQuestions :
                [{question:"Do you want a lift on your truck?",
                  answers: ["Yes","no"]
                  }
                 //More questions
                 ]
           }

至于 html,有一个模板,您可以在其中输入值(问题和答案)并每次都重复使用它。请记住,要访问truckQuestions,我们可以使用data.truckQuestions,也可以使用data['truckQuestions'],这允许我们重用data.genericQuestions[0].answers[1][1] 的值(希望这不会让您感到困惑)

【讨论】:

  • 是的,我有点困惑。我知道数组是如何工作的,也知道一些 JS,但是你的布局方式有点奇怪。它如何显示和隐藏问题,如何跟踪他们选择的答案...
  • 我提供的代码没有任何逻辑,它是您可以使用的问题的数据结构。您不会隐藏/显示问题,只需更新数据和答案。至于跟踪答案,这也取决于你,保留一系列答案,或者其他什么。为了澄清,你问如何减少代码冗余,我告诉你如何,我不是为你编码;)
  • 我意识到您不必编写代码,我只是想知道基础知识。比如我需要一个数组来保存卡车的所有问题,而一个数组来保存汽车的所有问题吗?然后一个答案?
  • 我会按照上面显示的方式进行操作,对于每个“分支”问题,您都需要一个新数组。因为根据答案,下一个问题会有所不同。另一种选择是将所有答案放在一个数组中,而不是在答案旁边放置下一个分支,而是拥有下一个问题的索引。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多