简体   繁体   English

如何在此javascript中获取多个随机不同的项目

[英]How to get more than one random different item in this javascript

I have this code that picks up a random text link using getJSON. 我有这段代码 ,可以使用getJSON拾取随机文本链接。 It picks up one random item at a time. 它一次拾取一个随机项。 I'd like to know how to pick up more than one different item and show them in #randomkeyword . 我想知道如何拿起一个以上的不同物品,并在#randomkeyword显示它们。 All I can come up with is setting up the script two times, but I think it may have a chance of picking up the same item, Is there any way to do that? 我所能想到的就是两次设置脚本,但是我认为它可能有机会选择相同的项目,有什么办法吗?

jQuery.getJSON('random.json', function(data) { //Ajax call

var item = data.link[Math.floor(Math.random()*data.link.length)]; 

jQuery('<a title="' + item.des + '" href="http://' + item.url + '">'+ item.title +'</a>').appendTo

('#randomkeyword');

});

JSON File: JSON档案:

{"link":[{"title":"XXXX","url":"google.com","des":"light"},{"title":"CCCCCCC","url":"yahoo.com","des":"dark"},{"title":"DDDDDDDD","url":"song.com","des":"light"},{"title":"CCCCCCCCCCCCCCC","url":"googlemap.com","des":"normal"},{"title":"RRRRRRRRRRRRRRR","url":"fun.com","des":"halo"}]}

为了避免重复,您可以“随机播放”列表,然后从头开始遍历。

You could check if the second item is the same as the first item. 您可以检查第二项是否与第一项相同。 If so, you can select an other random item. 如果是这样,您可以选择其他随机项目。

jQuery.getJSON('random.json', function(data) { //Ajax call

var item = data.link[Math.floor(Math.random()*data.link.length)];
var item2=item;//set second item same as first item to access the while loop

while(item==item2){
   item2 = data.link[Math.floor(Math.random()*data.link.length)];
}

jQuery('<a title="' + item.des + '" href="http://' + item.url + '">'+ item.title +'</a>').appendTo

('#randomkeyword');

});
//do the same for item2

So, I think you can store the list, then just iterate over it however many times you want, splice out the selected ones as you go (to avoid duplicates), and then run your jQuery on each element in the result array. 因此,我认为您可以存储列表,然后根据需要进行多次遍历,在运行时splice出选定的列表(以避免重复),然后在结果数组中的每个元素上运行jQuery。 Note that this does modify the returned array, so make a copy of it first if you need that intact. 请注意,这确实会修改返回的数组,因此,如果需要原样,请首先对其进行复制。

For example: 例如:

var data = ['one', 'two', 'three'];
var numOfLinks = 2;
var result = [];
for(i = 0; i < numOfLinks; i++) {
    var index = Math.floor(Math.random()*data.length);
    var link = data[index];
    data.splice(index,1);
    result.push(link);
}
// iterate over result, doing your jQuery function over each element

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM