【问题标题】:Only show one content at the time (using {{each}} on HTML)一次只显示一个内容(在 HTML 上使用 {{each}})
【发布时间】:2018-07-18 02:19:02
【问题描述】:

我正在使用把手{{each}} 来显示内容。

每个内容都在一个 div-box 中显示其数据,因此多个内容垂直显示,例如:

  ______
 |      |
 |      |
 |______|
  ______
 |      |
 |      |
 |______|

//.. 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}} 

有什么好的方法可以实现吗?

【问题讨论】:

  • handlerbar 是无逻辑的:如果您通过设计阻止模板中的逻辑(就像 mustache 那样)将逻辑放在其他地方,那么您的模板最终会整洁。
  • @M.Gara 我明白了,你能告诉我如何“把逻辑放在别处”吗?刚开始学习node.js等。另外,分页(一次显示一页)是一个解决方案还是一个坏主意?

标签: javascript html css node.js handlebars.js


【解决方案1】:

最好将逻辑放在javascript中。 eg:将当前成员存储在family obj上。

但车把确实有 if 语句,所以你可以做这样的 sn-p:

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>

【讨论】:

  • 当你按下“下一步”按钮时,sn-p 仍然显示相同的值
  • 按钮没有任何作用。 sn-p 只是为了表明您可以拥有 if 语句。
  • 我知道 if 语句,但我不知道如何使它工作。
  • 我回答了一次显示一个的问题。您现在是在问如何使按钮更改显示的按钮吗?
  • @ipid 我更新了 sn-p 以使用 jquery 处理点击事件。将按钮移到模板之外可能是个好主意,这样就不需要重新绑定单击事件。 Angular 通过为您处理更改,无需重新渲染或重新绑定,使这变得更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多