如何计算每个jquery模板中的项目并将if应用于该变量
类似
<script id="inventorySummaryTmpl" type="text/x-jquery-tmpl">
<tr>
{{each response}}
{{if response.length === 2 }}
</tr><tr>
{{/if}}
<td><img src='${icon}'> ${title} </td>
{{/each}}
</tr>
这是加载JSON并与jquery.TMPL
交互的javascript var ip = window.location.hash;
var request = $.ajax({
type: 'GET',
url: 'ajax/dashboard/widgets/inventorySummary.xsp?ip='+ip.substring(1),
dataType: 'json'
});
request.done(function(data){
$("#inventorySummaryTmpl").tmpl(data).appendTo("#inventorySummaryContent");
});
request.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus)
});
和JSON
{
"response": [
{
"icon": "workstation",
"nbItems": "38",
"title": "Workstations"
},
{
"icon": "server",
"nbItems": "2",
"title": "Servers"
}
]
}
如果有人有任何想法。
答案 0 :(得分:2)
你非常接近。 each
语句中的变量需要是您循环的完整集合。您还可以为集合中每个项目的索引和值传递自定义变量名称。根据您的代码,以下内容应该可以使用,但是如果您发布了集合的结构,我们就能确保它的确如此
<script id="inventorySummaryTmpl" type="text/x-jquery-tmpl">
<tr>
{{each(index,resp) responses}}
{{if resp.length === 2 }}
</tr><tr>
{{/if}}
<td><img src='${resp.icon}'> ${resp.title} </td>
{{/each}}
</tr>
jQuery文档:http://api.jquery.com/template-tag-each/
<强>更新强>
我已经更新了我的解决方案,因为我知道你在追求什么。如果要在ul
数组中的每三个(或六个或其他)元素之后开始新的tr
(或response
),请检查当前元素的索引,而不是完整响应数组的长度。
<script id="inventorySummaryTmpl" type="text/x-jquery-tmpl">
<ul>
{{each(i,el) response}}
{{if (i > 0 && i % 3 === 0) }}
</ul><ul>
{{/if}}
<li class="inventoryWrap">
<img src='blueprint/images/wrap/icons/${icon}.png' class="inventoryPic">
<span class="inventoryCount">${el.nbItems}</span>
<span class="inventoryText">${el.title}</span>
</li>
{{/each}}
</ul>
</script>