我正在使用把手{{each}}
显示内容。
每个内容在Div-Box中显示其数据,因此垂直显示多个内容,例如:
______
| |
| |
|______|
______
| |
| |
|______|
//.. and so on
相反,我想当时显示一个内容,并能够在按钮的帮助下更改下一个内容。
右下角有一个按钮,目前dos尚无任何操作。
______
| |
| |
|___[>]| //click on the button, and the next content will display
html/车把代码:
{{#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}}
有什么好方法可以实现这一目标?
最好将逻辑放入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();
}
<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>