【问题标题】:Using each to iterate over the passed in data使用 each 遍历传入的数据
【发布时间】:2011-12-06 06:31:47
【问题描述】:

如果将数组直接传递给 jquery 模板(而不是对象的属性),我该如何迭代它?

例如:

var hired=[{name:'Jack'}, {name:'Jack'}, {name:'Jack'}]

这是传递给下面模板的数据:

Template Start
<div> 

<table> 

{{each $data}}

<tr>
    <td width="250" align="left">${$value.name}</th>
    <td width="150" align="center">${$value.name}</th>
    <td width="60" align="center">${$value.name}</th>
</tr>
{{/each}}

</table>

</div>

Template End

由于没有属性名称来引用传入的数据,我尝试使用 $data 但它不起作用。我怎样才能在这里访问数组?

非常感谢。

【问题讨论】:

  • 我不确定 jQuery 模板是如何工作的,但在 javaScript 中,数组的行为类似于属性是元素索引的对象文字。因此,您示例中的数组与对象 {0:{name:'Jack'}, 1:{name:'Jack'}, 2:{name:'Jack' 相同(从每个循环的角度来看) }}

标签: jquery-templates jquery


【解决方案1】:

如果您将数组传递给tmpl,它将自动将模板应用于每个元素。这不是你想要的吗?

var hired = [{name:'Jack'}, {name:'Jack'}, {name:'Jack'}];

带模板:

<script id="hired-template" type="text/x-jquery-tmpl">
    <tr>
        <!-- I think you originally closed these with 'th' by mistake. -->
        <td width="250" align="left">${name}</td>
        <td width="150" align="center">${name}</td>
        <td width="60" align="center">${name}</td>
    </tr>
</script>

<table id="hired-table"></table>

这应该允许您这样做:

$('#hired-template').tmpl(hired).appendTo('#hired-table');

得到:

<table id="hired-table">
    <tr>
        <td width="250" align="left">Jack</td>
        <td width="150" align="center">Jack</td>
        <td width="60" align="center">Jack</td>
    </tr>
    <tr>
        <td width="250" align="left">Jack</td>
        <td width="150" align="center">Jack</td>
        <td width="60" align="center">Jack</td>
    </tr>
    <tr>
        <td width="250" align="left">Jack</td>
        <td width="150" align="center">Jack</td>
        <td width="60" align="center">Jack</td>
    </tr>
</table>

当然,我不确定你是否想让“杰克”一共出现九次;但这似乎是您的代码在运行时会执行的操作。

【讨论】:

  • 感谢您的回答,我知道这一点,但在我的情况下,我不能多次渲染模板,也不能使用子模板。有没有办法获取传递的数据对象?我已经在问题中编辑了我的模板。
【解决方案2】:

HTML:

<table id="tableID">
</table>

javascript:

var hired=[{name:'Jack'}, {name:'Jimmy'}, {name:'Ron'}]

    for( var i=0; i < hired.length; i++ ) {
        $( "#tableID" ).append(
          "<tr> \
            <td width=\"250\" align=\"left\">" + hired[ i ].name + "</td> \
            <td width=\"150\" align=\"center\"> " + hired[ i ].name + " </td> \
            <td width=\"60\" align=\"center\"> " + hired[ i ].name + " </td> \
           </tr>"
        );
    };

如果您有什么不明白的地方,请告诉我。

【讨论】:

  • 谢谢,但我正在寻找一个 jquery 模板特定的答案。
猜你喜欢
  • 2015-03-03
  • 1970-01-01
  • 2019-03-18
  • 2010-12-26
  • 2013-11-01
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
相关资源
最近更新 更多