簡體   English   中英

如何獲取隨機json數據並附加到div元素

[英]how to get random json data and append to div element

說這是我的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-twitter 3-social

現在我的問題是我想隨機獲取這些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。

您需要創建一組隨機唯一數字,如下所示:

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);
});

一個簡單的演示

你應該創建一個'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;
    });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM