Why are JavaScript string arrays interpreted differently by jQuery template {{each}} tags vs. jQuery $.each?

柔情痞子 提交于 2019-12-07 07:46:17

问题


Obligatory jsFiddle example.

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", ...)
});

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");

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").

Follow-up question

@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.


回答1:


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/ 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 will add the indexing back in using a function. For some reason, I can't do it properly with a closure.



来源:https://stackoverflow.com/questions/7434667/why-are-javascript-string-arrays-interpreted-differently-by-jquery-template-ea

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