如何使{{#each}}在特定条件下停止迭代

时间:2013-07-27 21:31:32

标签: javascript jquery templates iteration handlebars.js

所以我试着做一个小测验,我希望每个问题都有他的选择显示,当用户点击下一个按钮时,当前的问题被删除,下一个选项是beign showen。 类似的东西:

问:什么? 选择:1-a,2-b,3-c,4-d

“下一步”按钮。

并点击下一步删除当前问题(也是选项) 然后出现下一个问题: 问题:为什么? 选择:1-z,2-x,3-y,4-r

“下一步”按钮

这是我的HTML代码:

<div class="well span6 offset3">
            <script id="try" type="text/x-handlebars-template">
                <form>
                    <fieldset>
                        <legend>Login</legend>
                        <input id="fn" type="text" name="userF" class="input-block-level" placeholder="First Name">
                        <input id="ln" type="text" name="userL" class="input-block-level" placeholder="Last Name">
                        <input id="login" type="submit" class="btn btn-primary" value="login">
                    </fieldset>
                </form>
                {{#each this}}
                <div><h4>{{question}}</h4></div>
                <ul>
                {{#each choices}}
                <li><input type="radio" name="{{../question}}" value="{{this}}">{{this}}</li>
                {{/each}}
                </ul>
                {{/each}}
                <input type="submit" id="next" class="btn btn-primary" value="Next" placeholder="Next">
            </script>

这是我的数组:

var allQuestions = [
    new QuestionCreate("Which is the Capital of Australia?", ["Syndey", "Canberra", "Melbourne", "Hobart"], 2),
    new QuestionCreate("How much population there is in Australia?", ["22M", "18m", "20M", "23M"], 4),
    new QuestionCreate("How is the most expensive soccer player ever?", ["Cristiano Ronaldo", "Messi", "Zlatan Ibrahimovic", "Luis Figo"], 1),
    new QuestionCreate("Which national team as the most wins in the Fifa World Cup?", ["Italy", "Spain", "Brazil", "England"], 3)
];

这是我的编译:     theTemplateScript = $(“#try”)。html();

var theTemplate = Handlebars.compile(theTemplateScript);

$(".offset3").append(theTemplate(allQuestions));

2 个答案:

答案 0 :(得分:1)

也许你在渲染第一个问题后可以做这样的事情:

var counter = 0 
$("#next").click(function() {
  $(".offset3").html("")
  counter = counter + 1 
  $(".offset3").append(theTemplate(allQuestions[counter]));
});

答案 1 :(得分:0)

与事件委托一起工作:

theTemplateScript = $("#try").html();

var theTemplate = Handlebars.compile(theTemplateScript);

var counter = 0

$(".offset3").append(theTemplate(allQuestions[counter]));

$("div").on("click","#next", function() {
    $(".offset3").html("")
    counter = counter + 1
    $(".offset3").append(theTemplate(allQuestions[counter]));
    return counter;
});