![](/img/trans.png)
[英]How can I prevent function inside of forEach loop from being called more than once? (For the most part it repeats predictably)
[英]Prevent tag inside template loop from being output more than once?
我正在嘗試創建一個表,該表的id
單元格應基於sessions
數組的長度跨越3列,現在,因為id
單元格在循環內,當我只希望它具有一次功能時它會輸出3次。 是否可以在模板中進行設置?
JS
<table>
<tbody class="js-output">
<script type="text/html" id="tmpl">
<% _.each(sessions, function(session) { %>
<tr>
<td rowspan="<%- session.length %>"><%- id %></td>
<td><%- session %></td>
<td><select name="" id=""></select></td>
</tr>
<% }) %>
</script>
</tbody>
</table>
小提琴: https : //jsfiddle.net/egks4ys1/
硬編碼布局: https : //jsfiddle.net/egks4ys1/1/
這是一個模板,用於與其他元素分開處理第一個session元素。
<table>
<tbody class="js-output">
<script type="text/html" id="tmpl">
<tr>
<td rowspan="<%- sessions.length %>"><%- id %></td>
<td><%- _.first(sessions) %></td>
<td><select name="" id=""></select></td>
</tr>
<% _.each(_.rest(sessions), function(session) { %>
<tr>
<td><%- session %></td>
<td><select name="" id=""></select></td>
</tr>
<% }) %>
</script>
</tbody>
</table>
小提琴: https : //jsfiddle.net/egks4ys1/6/
我已經使用了index
和if
構造,如下所示:
<table>
<tbody class="js-output">
<script type="text/html" id="tmpl">
<% _.each(sessions, function(session,i) { %>
<tr>
<% if(i!=0){ %>
<td><%- session %></td>
<td><select name="" id=""></select></td> <%}%>
<% if(i==0){%> <td rowspan="<%- sessions.length %>"><%- id %></td>
<td><%- session %></td>
<td><select name="" id=""></select></td><%}%>
</tr>
<% }) %>
</script>
</tbody>
JSFiddle: https ://jsfiddle.net/egks4ys1/14/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.