强制性的jsFiddle 示例 http://jsfiddle.net/patridge/wuEyp/.
当我通过 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}}
运算符,但是,它将其视为二维数组char
s.
<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 确实在这里解释了这个问题。不幸的是,鉴于这是我实际代码的子集,结果只是带来了不同的结果关于递归调用的问题{{each}}当你遇到字符串数组时的模板 https://stackoverflow.com/questions/7436189/how-do-i-prevent-jquery-template-from-digging-too-deeply-on-a-string-array-in-a-r.