如何获取随机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推特 3-社交
the same continues but there are 3 types 1-employee 2-twitter 3-social
现在我的问题是我想随机获取这些json数据并追加到我的div元素中 我使用了以下代码
Now my problem is I want get these json data randomly and append to my div element I used following code
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);
});
我知道如何使用以下代码生成单个随机条目
I know how to generate single random entry using following code
entry = data[Math.floor(Math.random()*data.length)];
生成一个随机条目.
请帮助我如何从上面的json文件中随机获取json数据并追加到div.
Plz help me how to get json data randomly from above json file and append to div.
推荐答案
您需要制作一个随机的唯一数字数组,如下所示:
You need to make an array of random unique numbers like following:
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;
}
然后您需要遍历数据,如下所示:
Then you need to loop over data like following:
在这里,我遍历唯一数组,而不是在data
上,并使用数组的值作为data
的索引.
Here I am looping over unique array, not on data
and using value of array as index to 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
这篇关于如何获取随机json数据并追加到div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!