【发布时间】:2011-11-18 01:53:30
【问题描述】:
当我通过 jQuery 的 $.each 函数运行一个字符串数组时,我得到了我期望的结果。
$.each(["abc", "123", "def", "456"], function (i, val) {
$("<li></li>").text("source[" + i + "]: " + val).appendTo(".eachResults");
// run for each string in the array ("abc", "123", ...)
});
但是,当我通过 jQuery 模板的 {{each}} 运算符运行相同的字符串数组时,它会将其视为 chars 的二维数组。
<script id="testTemplate" type="text/x-jquery-tmpl">
<ul>
{{each(i, prop) $data}}
{{if $data.hasOwnProperty(i)}}
<li>
source[${i}]: ${$data[i]}
{{! run for each char of each string in array (0:"a", 1:"b", 2:"c", 0:"1", 1:"2", 3:"3", ...)}}
</li>
{{/if}}
{{/each}}
</ul>
</script>
$("#testTemplate").tmpl(["abc", "123", "def", "456"]).appendTo(".tmplResults");
由于模板中的i 似乎总是正确地引用到$data,所以我根本不知道这个索引是如何工作的。似乎i 需要是二维索引才能正常工作,但它似乎不是 (typeof (i) === "number")。
跟进问题
@mblase75 在这里肯定解释了这个问题。不幸的是,考虑到这是我实际代码的一个子集,结果只是提出了一个不同的question about recursively calling an {{each}} template when you come across an array of strings。
【问题讨论】: