0

我有一个 JavaScript 数组:

var personDetails = [
{firstName: "Anup", lastName: "Vasudeva", City: "Delhi"},
{firstName: "Vikas", lastName: "Kumar", City: "Banglore"},
{firstName: "Dannis", lastName: "Richie", City: "Texas"},
{firstName: "Ajay", lastName: "Sharma", City: "Pune"},
{firstName: "Deepak", lastName: "Aggarwal", City: "Delhi"},
{firstName: "Ajay", lastName: "Sharma", City: "Banglore"}

]

这是我打算设计的模板:

<div class="left">
     <!-- Should display the first half of the rows -->
     {{tmpl($data) "#someTemplate"}}
</div>
<div class="right">
    <!-- Should display the rest half of the rows -->
    {{tmpl($data) "#personTemplate"}}   
</div>

<script id="personTemplate" type="text/x-jquery-tmpl">
{{each personDetails}}
    <div class="person">
        <div>${firstName}</div>
        <div>${lastName}</div>
        <div>${city}</div>
    </div>
{{/each}}

如何操作包含前半部分行并包含后半部分行的数组。

编辑:实际上问题是用户将按原样传递数组,并且模板逻辑将数组切成两半。

谢谢阅读。

4

2 回答 2

0

使用Array.slice将您的输入分成两半:

var input = [
    {firstName: "Anup", lastName: "Vasudeva", City: "Delhi"},
    {firstName: "Vikas", lastName: "Kumar", City: "Banglore"},
    {firstName: "Dannis", lastName: "Richie", City: "Texas"},
    {firstName: "Ajay", lastName: "Sharma", City: "Pune"},
    {firstName: "Deepak", lastName: "Aggarwal", City: "Delhi"},
    {firstName: "Ajay", lastName: "Sharma", City: "Banglore"}
];

var half_point = Math.floor(input.length / 2);
var first_half  = input.slice(0, half_point);
var second_half = input.slice(half_point+1)

console.log(first_half, second_half)

更新

我不确定您为什么要在模板本身中执行此操作,我建议您将此逻辑移动到数据旁边,也许可以通过向Array对象添加方法:

Array.prototype.chunk = function(chunk_count, chunk_no) {
    var chunk_size = Math.floor(this.length / chunk_count);
    return this.slice(chunk_no * chunk_size, chunk_size + chunk_no * chunk_size);
}

...并从模板的 each 方法中调用它,如下所示:

<script id="personTemplate" type="text/x-jquery-tmpl">
<div class="left">
    {{each data.chunk(2, 0)}}
    <div class="person">
        <div>${firstName}</div>
        <div>${lastName}</div>
        <div>${city}</div>
    </div>
    {{/each}}
</div>
<div class="right">
    {{each data.chunk(2, 1)}}
    <div class="person">
        <div>${firstName}</div>
        <div>${lastName}</div>
        <div>${city}</div>
    </div>
    {{/each}}
</div>
</script>

扩展(在其他圈子中为“monkeypatching”)核心类是否是一个好主意是有争议的,您也可以将相同的函数直接添加到您的input变量中。然而,在渲染之前使用分配给模板的两个单独的变量可能会导致更少的意外,因此可能会更有利。

于 2012-08-29T06:12:37.230 回答
0

不要使用模板以这种方式操作数据。在将用户给定的数组提供给模板之前,请在外部执行此操作。您不想这样做的原因是,如果您让模板来处理这样的逻辑,那将比在外部执行它要慢得多。这对于 10-20 个项目的数组来说并不明显,但如果数组由于某种原因而变大,那么模板会明显变慢。

于 2012-08-29T06:25:53.093 回答