循环通过带下划线的范围内的json

时间:2014-12-17 11:16:01

标签: underscore.js

我循环浏览json文件,如下所示:

 <% _.each( looks, function( listItem, index ){ %>
                <li >
                    <a href="javascript:showDetailsView(<%= index %>)" class="look-btn" id="<%= listItem.id %>" data-look-id="<%= index %>">                        
                        <img src="<%= listItem.image %>" alt="<%= listItem.id %>"/>

                        <span class="seeLook"><localize id="13">See the Look</localize></span>
                    </a>
                </  li >
            <% }) %>

但是我只想循环说出JSON文件中的前5项,或10-14项,我该怎么做?

json文件如下:

looks = [      
        {
        "id" : "look1",
        "image" : "/img/304x535/look1.jpg?$staticlink$",
        "imageLarge" : "/img/436x768/look1.jpg?$staticlink$",
        "products" : [
"hbeu50271612", "hbeu50274694", "hbeu50272802", "hbeu50276781", "hbeu50274296", "hbeu50272359"
]
        }
        ,
        {
        "id" : "look2",
        "image" : "/img/304x535/look2.jpg",
        "imageLarge" : "/img/436x768/look2.jpg",
        "products" : [
"hbeu50274106", "hbeu50273647", "hbeu50274754", "hbeu50274063", "hbeu50274911", "hbeu50274106", "hbeu50240022", "hbeu50271944"]
        },
......

1 个答案:

答案 0 :(得分:0)

我已经为您制定了一个解决方案,使用下划线核心和一些javascript数组功能,希望这对您有用,请根据您的解决方案进行编辑,我在演示中使用了较少的元素,但这是一个使用下划线从集合中选择任何范围的一般解决方案 链接:http://jsfiddle.net/ohx0chke/21/

   <h1>Result List</h1>
    <div id="result"></div>
    <script type="text/template" id="look-template">
    <% _.each( looks, function( look){ 
        var listIndex = looks.indexOf(look)+1;
        if( listIndex >= start & listIndex <= end){
        %>
            <h1>pirnt ----<%- look.id %></h1>
    <% } }) %>
    </scirpt>

    var looks = [
           {
                'id' : 'look1',
                'uid' : '54915a9f4f26e',
                'unixtimestamp' : 1408210200
            },
           {
               'id' : 'look2',
               'uid' : '54915a9f519a2',
               'unixtimestamp' : 1408815000
            },
            {
               'id' : 'look3',
               'uid' : '54915a9f519a2',
               'unixtimestamp': 1408814467
            },
             {
               'id' : 'look4',
               'uid' : '54915a9f519a2',
               'unixtimestamp' : 1408815000
            },
            {
               'id' : 'look5',
               'uid' : '54915a9f519a2',
               'unixtimestamp': 1408814467
            }
            ,
            {
               'id' : 'look6',
               'uid' : '54915a9f519a2',
               'unixtimestamp': 1408814467
            }

    ];

    function print_list(start, end, datalist){           
        var compiled = _.template($('#look-template').html());    
        $('#result').html(compiled({looks: datalist, start: start, end: end}));
    } 

    print_list(2, 4, looks);