在jQuery模板中获取当前项目索引的最简单方法 [英] Simplest way to get current item index within jQuery template
问题描述
我正在将对象数组传递给jQuery模板(官方jquery-tmpl
插件):
I am passing an array of objects to jQuery template (official jquery-tmpl
plugin):
$("#itemTmpl").tmpl(items).appendTo("body");
<script id="itemTmpl" type="text/x-jquery-tmpl">
<div class="item">Name: ${name}, Index: ${???}</div>
</script>
在模板中显示项目索引的最简单方法是什么?最好不使用单独的外部函数,不更改传递的对象结构,也不更改模板结构(转换为{{each}}
).可能有任何内置变量存储当前数组索引吗?
What is the easiest way to display item index in the template? Preferably without using separated external functions, without changing passed object structure, and without changing template structure (converting to {{each}}
). Is there any built-in variable perhaps that stores current array index?
更新 我创建了一张票据,提议将数组索引暴露给模板项,但是由于无效而被关闭了...
UPDATE I created a ticket proposing to expose array index to template item but it was closed as invalid...
推荐答案
好吧,它不是 true 单独的外部函数,但是您可以将函数拍打到options
对象上,然后将其传递给tmpl
.我已经完成了以下工作,并且工作正常:
Well, it's not a true separate external function, but you can slap a function onto the options
object you can pass to tmpl
. I've done the following and it works fine:
$("#templateToRender").tmpl(jsonData,
{
dataArrayIndex: function (item) {
return $.inArray(item, jsonData);
}
});
在模板中,您可以从$item
对象访问该功能:
In the template, you can access the function from the $item
object:
<script id="templateToRender" type="text/x-jquery-tmpl">
<li>
Info # ${$item.dataArrayIndex($item.data)}
</li>
</script>
或者,代替将$item.data
传递到函数中,该函数的上下文是模板的tmplItem
对象(与$ item.data相同).因此,您可以将dataArrayIndex
编写为无参数,然后通过this.data
访问数据.
Alternatively, instead of passing $item.data
into the function, the context of the function is the tmplItem
object of the template (same as $item.data). So you could write dataArrayIndex
as parameterless and access the data via this.data
.
这篇关于在jQuery模板中获取当前项目索引的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!