2011-12-20 70 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>