我使用把手{{each}}
来显示内容。
每个内容在div框中显示其数据,因此垂直显示多个内容,如:
______
| |
| |
|______|
______
| |
| |
|______|
//.. and so on
相反,我想在当时显示一个内容,并且可以借助按钮更改为下一个内容。
右下角有一个按钮,暂时不做任何事情。
______
| |
| |
|___[>]| //click on the button, and the next content will display
HTML / Handlebar代码:
{{#each family}}
<div class="content-wrapper">
<h1>{{surName}}</h1>
{{#each member}}
<h2>{{firstName}}</h2>
{{/each}}
<button id="btn-next" type="submit">Next</button>
</div>
{{/each}}
有没有什么好方法可以实现这个目标?
答案 0 :(得分:1)
最好将逻辑放在javascript中。例如:将当前成员存储在家庭对象上。
但是把手确实有if语句,所以你可以做这样的代码片段:
var context = {
surName: 'last',
selectedIdx: 0, // zero based index of selected family member
member: null, // selected family member for handlebars
members: [
{ firstName: 'first1', surName: 'last' },
{ firstName: 'first2', surName: 'last' },
{ firstName: 'first3', surName: 'last' },
],
};
render();
function render() {
// set selected member for handlebars
context.member = context.members[context.selectedIdx]
var source = document.getElementById("fam-template").innerHTML;
var template = Handlebars.compile(source);
document.getElementById("fam").innerHTML = template(context);
// bind to click event of button added above
// this needs to be done each time the next button is clicked
// since the button is inside the handlebars template
$("#btn-next").click(handleClick);
}
function handleClick() {
// move to next family member
context.selectedIdx++;
// wrap around
if (context.selectedIdx >= context.members.length) {
context.selectedIdx = 0;
}
// re-render
render();
}
&#13;
<script id="fam-template" type="text/x-handlebars-template">
<div class="content-wrapper">
<h1>{{surName}}</h1>
<h2>{{member.firstName}}</h2>
<button id="btn-next" type="submit">Next</button>
</div>
</script>
<div id="fam"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;