2

我有一个带有以下数据的 JSON 文件(只是我所拥有的一个示例),并且我正在将此数据与handlebars.js一起使用来创建模板。

我遇到的问题是我需要在页面加载时显示 15 个故事(在他们的 div 中),但是在每次页面刷新时,我希望这些故事位于页面上的不同位置。

我想我最简单的问题是 - 我如何随机化每个项目并且仍然只显示 15 个故事?

这是我的 JSON 文件的示例(但想象一下超过 20 个故事)

{
    "stories": [{
        "realTime": [{
            "id": "realTime",
                "icon": "link",
                "info": {
                "title": "Video box",
                    "type": "Link",
                    "description": "Lorem ipsum dolor ... elit nonummy quis",
                    "linkCopy": "Read more",
                    "link": "http://twitter.com"
            }
        }, {
            "id": "realWorld",
                "icon": "file-text",
                "info": {
                "title": "PDF box",
                    "type": "PDF",
                    "description": "Lorem ipsum dolor ... elit nonummy quis",
                    "linkCopy": "Read more",
                    "link": "http://www.google.co.uk"
            }
        }, {
            "id": "realResults",
                "icon": "comments",
                "info": {
                "title": "Blog here",
                    "type": "Blog",
                    "description": "Lorem ipsum dolor ... elit nonummy quis",
                    "linkCopy": "Read more",
                    "link": "http://www.google.co.uk"
            }
        }, {
            "id": "realTime",
                "icon": "comments",
                "info": {
                "title": "Blog here",
                    "type": "Blog",
                    "description": "Lorem ipsum dolor ... elit nonummy quis",
                    "linkCopy": "Read more",
                    "link": "http://www.google.co.uk"
            }
        }]
    }]
}

这是我用来检索 JSON 数据的 jQuery 以及handlebars.js编译代码。

$.getJSON('./assets/json/stories.json', function(data) {
        var source   = $("#block-template").html();
        var template = Handlebars.compile(source);
        $('#block-div').html(template(data));
});
4

1 回答 1

3

您可以使用_.sample从列表中获取 n 个随机元素:

var sample = _.sample(data.stories[0].realTime, 15);
var template = Handlebars.compile(sample);
于 2013-10-16T21:51:42.847 回答