Get Index in jQuery template

▼魔方 西西 提交于 2019-12-06 22:58:13

问题


I am using the jQuery template plugin and don't know how to get the index of items: http://api.jquery.com/category/plugins/templates/

Here is my code:

<script id="optionTmpl" type="text/x-jquery-tmpl">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
    {{each Answers}}
        <tr>
            <th><input type="radio" name="group1" value="${this.AnswerID}" /></th>
            <td>${this.AnswerText}</td><!-- add number in this line--->
        </tr>
    {{/each}}  
    </table>
</script>

I want to show the answer in the format like the following

1)answer1, 2)answer2, 3)answer3

or

a)answer1, b)answer2, c)answer3

What should I do?


回答1:


There's an implicit $index (and $value) available inside the {{each}} loop, you can use that here:

<script id="optionTmpl" type="text/x-jquery-tmpl">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
    {{each Answers}}
        <tr>
            <th><input type="radio" name="group1" value="${this.AnswerID}" /></th>
            <td>${this.AnswerText} ${$index + 1}</td>
        </tr>
    {{/each}}  
    </table>
</script>

You'll probably want to add 1 because it's 0-based, like I have above.



来源:https://stackoverflow.com/questions/4213033/get-index-in-jquery-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!