Random URL JS with Multiple Lists
I have a navigation bar and I want to access a random URL from a distinct list associated with each link. Link A would access List A, link B would access List B, and so on. I have 开发者_如何转开发been using a javascript code from 1997 that works great for one link:
<--code contained in a js file:-->
rnd.today=new Date();
rnd.seed=rnd.today.getTime();
function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280;
return rnd.seed/(233280.0);
};
function rand(number) {
return Math.ceil(rnd()*number);
};
var item = 0;
var URL = new Array();
URL[item++] = 'listitema.php';
URL[item++] = 'listitemb.php.php';
URL[item++] = 'listitemc.php';
function randomJump() {
var random = rand(item) - 1;
location.href = URL[random];
};
<--end js file:-->
This is accessed with this:
<a href="javascript:randomJump()" onmouseover="self.status='';return true">
While this code works well for one link per page, I now need to have it work for multiple links, each with a different reference list. I have no idea how to make this a script that works for each link without interfering with other links. Thank you.
Here's a small function that works with as many different URL lists as you want:
var listA = [
'listitem-a.php',
'listitem-b.php',
'listitem-c.php'
];
var listB = [
'listitem-1.php',
'listitem-2.php',
'listitem-3.php'
];
var listC = [
'listitem-x.php',
'listitem-y.php',
'listitem-z.php'
];
function goRandomURL(list) {
window.location = list[Math.floor(Math.random() * list.length)];
}
Then, to use listA
, you would call:
goRandomURL(listA);
or put it in a link like this:
<a href="#" onclick="goRandomURL(listA)">
or for listB, you would use this:
<a href="#" onclick="goRandomURL(listB)">
For your own reference, the javascript Math.random()
function returns a random number as a float between 0 and 1 (not including 1) and it's already seeded based on the local environment so you don't need to introduce your own seed or random functions. The random number is then scaled by the length of the array passed in and then rounded down to a whole number for array indexing. This has the effect of selecting a random index to our array. It automatically tracks the length of the array so you are free to add/remove items from the array without changing the code in any way.
EDIT - to help you on your current code. In your current code, I see this:
var listA = [
'orange.php';
'red.php';
'blue.php';
];
var listB = [
'gold.php';
'silver.php';
'bronze.php';
];
var listC = [
'olive.php';
'pink.php';
'purple.php';
];
It should be this:
var listA = [
'orange.php',
'red.php',
'blue.php'
];
var listB = [
'gold.php',
'silver.php',
'bronze.php'
];
var listC = [
'olive.php',
'pink.php',
'purple.php'
];
And this:
goRandomURL(list) {
window.location = list[Math.floor(Math.random() * list.length)];
}
should be this:
function goRandomURL(list) {
window.location = list[Math.floor(Math.random() * list.length)];
}
精彩评论