2010-12-12 70 views
2

不,這不是重複的this question ......雖然有點相關,所以我將使用來自該Q的代碼進行比較。在jquery tmpl中獲取索引

我試圖從嵌套模板中使用{{tmpl}} tag獲取索引。使用tmlp標記與上面鏈接的問題中的{{each}}標記非常相似,但$ index屬性不存在。

<script id="answerTable" type="text/x-jquery-tmpl"> 
    <table width="100%" border="0" cellspacing="0" cellpadding="0"> 
    {{tmpl(answersObj) '#answers' }} 
    </table> 
</script> 

<script id="answers" type="text/x-jquery-tmpl"> 
    <tr> 
     <th><input type="radio" name="group1" value="---!INDEX HERE!---" /></th> 
     <td>${AnswerText}</td> 
    </tr> 
</script> 

我不想用一個混亂的方式做這個 - 我寧願如果可以修改的lib拉閘。任何人有任何想法可以修改當前的lib來支持這個功能 - git hub source。這段代碼稍微超過我的腦袋,時間緊迫,並且理解這個lib不在我目前的項目範圍之內;)

+1

小怪想要臨時代表 – 2010-12-14 02:11:23

+0

哈。那麼你不能補充賞金,除非你有至少75 ...反正我自己回答Q.所以不需要投票... – user406905 2010-12-14 02:14:38

+0

並等待兩天 – 2010-12-14 02:16:51

回答

3

OK必須修改模板庫。 請參閱this link for github補丁。 jquery.tmpl.js的原始(當前版本)

線150-155

ret = jQuery.isArray(data) ? 
     jQuery.map(data, function(dataItem) { 
     return dataItem ? newTmplItem(options, parentItem, tmpl, dataItem) : null; 
     }) : 
     [ newTmplItem(options, parentItem, tmpl, data) ]; 
return topLevel ? jQuery(build(parentItem, null, ret)) : ret; 

修改,以支持$指數

ret = jQuery.isArray(data) ? 
     jQuery.map(data, function(dataItem, index) { 
     if(dataItem){dataItem.$index = index;} 
     return dataItem ? newTmplItem(options, parentItem, tmpl, dataItem) : null; 
     }) : 
     [ newTmplItem(options, parentItem, tmpl, data) ]; 
return topLevel ? jQuery(build(parentItem, null, ret)) : ret; 
0

我也學會了另一種技術的可能會或可能不適合你的場景...

你可以使用jQuery.inArray從父數據對象獲取索引 - 假設你keepin g同步父數據對象。