为什么jQuery模板{{each}}标签与jQuery $ .each对JavaScript字符串数组的解释不同? [英] Why are JavaScript string arrays interpreted differently by jQuery template {{each}} tags vs. jQuery $.each?

查看:114
本文介绍了为什么jQuery模板{{each}}标签与jQuery $ .each对JavaScript字符串数组的解释不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必填 jsFiddle示例.

当我通过jQuery的$.each函数运行字符串数组时,我得到了期望的结果.

When I run an array of strings through jQuery's $.each function, I get what I expect.

$.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 Template的{{each}}运算符运行相同的字符串数组时,它将其视为char s的二维数组.

When I run the same array of strings through jQuery Template's {{each}} operator, though, it treats it as a two dimensional array of 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").

Since the i in the template always seems to reference correctly into $data, I don't really have any clue how this indexing works at all. It seems like i would need to be a two-dimensional index to work correctly, but it doesn't appear to be (typeof (i) === "number").

@ mblase75在这里肯定解释了这个问题.不幸的是,考虑到这只是我实际代码的一部分,结果只是显示了一个不同的

@mblase75 certainly explained the issue here. Unfortunately, given this was a subset of my actual code, it turned out to just bring up a different question about recursively calling an {{each}} template when you come across an array of strings.

推荐答案

请记住,模板是一个隐式循环.原始的{{each}}遍历每个字符串中的每个字符-模板遍历数组中的每个字符串.

Remember that templates are an implicit loop. Your original {{each}} was looping through each character in each string -- the template was looping through each string in the array.

这将为您提供所需的结果(或多或少):

This will give you the desired result (more or less):

<script id="testTemplate" type="text/x-jquery-tmpl"> 
    <li>
        source[]: ${$data}
    </li>
</script>

http://jsfiddle.net/wuEyp/10/使用上述代码.索引消失了,因为模板似乎没有在根"级别提供索引.

http://jsfiddle.net/wuEyp/10/ uses the above code. The index is gone because the template doesn't seem to provide for it at the "root" level.

http://jsfiddle.net/wuEyp/11 将使用函数添加索引.出于某种原因,我无法通过关闭操作正确地完成该操作.

http://jsfiddle.net/wuEyp/11 will add the indexing back in using a function. For some reason, I can't do it properly with a closure.

这篇关于为什么jQuery模板{{each}}标签与jQuery $ .each对JavaScript字符串数组的解释不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆