不,这不是 this question 的重复...不过有点相关,所以我将使用该 Q 中的代码进行比较。
我正在尝试使用 {{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>
我不想以一种困惑的方式来完成此操作 - 如果可能的话,我更愿意修改库。任何人都有任何想法可以修改当前的库以支持此功能 - git hub source 。这段代码有点超出了我的理解范围,我的时间很短,并且理解这个库不在我当前的项目范围内;)
最佳答案
好吧,必须修改模板库。 请参阅this link用于 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;
修改为支持$index
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;
关于javascript - 获取 jquery tmpl 中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4424757/