【问题标题】:Get index within jquery tmpl在jquery tmpl中获取索引
【发布时间】:2010-12-12 23:37:33
【问题描述】:

不,这不是 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。这段代码有点过头了,我的时间很短,理解这个库不在我目前的项目范围内;)

【问题讨论】:

  • 有点奇怪想要临时代表
  • 哈哈。好吧,除非您至少有 75 个,否则您无法添加赏金……无论如何,我自己回答了 Q。所以不需要投票......

标签: javascript jquery jquery-templates


【解决方案1】:

OK 不得不修改模板库。 github补丁见this link

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;

【讨论】:

    【解决方案2】:

    我还了解了另一种可能适用于您的场景的技术...

    您可以使用 jQuery.inArray 从父数据对象获取索引 - 假设您保持父数据对象同步。

    【讨论】:

      猜你喜欢
      • 2011-08-28
      • 2016-01-03
      • 2011-05-11
      • 2012-04-10
      • 2011-04-14
      • 2021-11-18
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多