2011-12-20 76 views
0

我有以下jQuery模板,我需要跟踪应用某些类的迭代次数。我尝试过所有我能想到的标准JavaScript变体。jQuery模板循环计数器

如何迭代$ i,然后在模板中引用$ i?

<script type="text/html"id="sectionTemplate">       <span data-bind="css: { selected: $data == viewModel.selectedSection() }, click: function(i) { viewModel.selectSection($data) }"> 
${i++} 
<input id="radio" class="ui-helper-hidden-accessible" type="radio" name="radio"> 
<label class="class${i}" for="radio${i}" aria-pressed="false" role="button" aria-disabled="false"> 
<span class="ui-button-text">${$data}</span></label>          
</span> 

+0

jQuery的模板不支持添加逻辑里面的代码,如果你需要,即,尝试其他的模板引擎,比如' doT'或'blueimp' https://github.com/blueimp/JavaScript-Templates – 2011-12-20 18:07:53

回答

2

调用模板内的外部函数可以完成你所需要的。

<script type="text/javascript"> 
    var i = 0; 
    function count() 
    { 
     return i++; 
    } 
</script> 

然后你在你的模板调用它是这样的:

<script id="sectionTemplate" type="text/x-jQuery-tmpl"> 
    ${count()} 
</script>