如何获取随机json数据并附加到div元素

时间:2012-06-03 13:59:02

标签: javascript jquery json

说这是我的json

[
{
    "imageSmall": ["images/employee_jpgs/employees_abhishek_80x80.jpg"],
    "imageBig": ["images/employee_jpgs/employees_abhishek_150x150.jpg"],
    "name": ["Abhishek Shet"],
    "quotes": ["Just perfect to start your career after school. Makes me feel        others in the industry are way slower then us. Awesome team and and a brilliant product to work on!!!!. And most importantly I enjoy what I do :)."],
    "type": "employee"
},
{
    "imageSmall": ["images/employee_jpgs/employees_barbra_80x80.jpg"],
    "imageBig": ["images/employee_jpgs/employees_barbra_150x150.jpg"],
    "name": ["Barbra Gago"],
    "quotes": ["The best part about working at tibbr is how dynamic the environment is, there's a lot of flexibility and freedom to execute on new ideas. Because everyone is so talented, there is a ton of trust and support coming from managers and team members-we all count on each other to do the best possible job!"],
    "type": "employee"
},

同样继续但有3种类型 1-雇员 2-叽叽喳喳 3-社会

现在我的问题是我想随机获取这些json数据并附加到我的div元素 我使用了以下代码

function(args){
 var me=this;
 $.getJSON(args.json,function(data) { 
 me.set(args);
 $.each(data, function(i){
    var id="randomizr_item_" + i;
    var temp= $('<div id='+ id +' class="randomizr-grid-items"><img src="'+ this.imageSmall[0]  +'" /></div>');
    me.config.container.append(temp);
    this.target=$(temp);
});

我知道如何使用以下代码生成单个随机条目

entry = data[Math.floor(Math.random()*data.length)];

生成单个随机条目。

Plz帮助我如何从json文件中随机获取json数据并附加到div。

2 个答案:

答案 0 :(得分:1)

您需要制作一组随机唯一数字,如下所示:

function generateRandom(min, max) {
    var arr = [];
    while(arr.length < 5){
      var randNum = Math.floor(Math.random() * (max - min + 1)) + min,
          found=false;
      for(var i=0;i < arr.length; i++){
        if(arr[i] == randNum){found=true;break}
      }
      if(!found)arr[arr.length] = randNum;
    }
    return arr;
}

然后你需要循环遍历以下数据:

这里我循环遍历唯一数组,而不是data并使用数组值作为data的索引。

var orders = generateRandom(0, data.length-1);

$.each(orders, function(index, value){
    var id="randomizr_item_" + i;
    var temp= $('<div id='+ id +' class="randomizr-grid-items"><img src="'+ data[value].imageSmall[0]  +'" /></div>');
    me.config.container.append(temp);
    this.target=$(temp);
});

<强> A simple demo

答案 1 :(得分:0)

你应该创建一个'Deck'并用json数据填充它。

一旦甲板被填满,在它有元素的情况下循环它,如下所示:

while(deck.length > 0) {
 var random_index = Math.floor(Math.random()*data.length);
 var item = deck[random_index];
 // do stuff with item
 deck = jQuery.removeFromArray(random_index, deck);
}

将此代码添加到js文件的顶部:

jQuery.removeFromArray = function(value, arr) {
    return jQuery.grep(arr, function(elem, index) {
        return elem !== value;
    });
};