# 如何实现多域名随机跳转？

Naturally
• 36

1.如何实现多域名随机跳转？同一个链接可以指向随机域名？
2.比如说，链接a这次跳转到链接b,下一次，可能是链接c，跳转的链接是随机的，在代码中如何实现呢？

3 个回答

``````location.href = Math.random() < 0.5 ? "http://www.foo.com" : "http://www.bar.com";
``````
``loaction.href = 'xxx.com/xxx'+Math.random();``

mqycn
• 2.1k

``````<%
'定义URL数据
urlData = split("http://www.baidu.com/|http://www.alibaba.com/|http://www.qq.com/|http://www.taobao.com/", "|")

'下面都是一样的代码
dim countData()
redim countData(0)

function getRandomLink(byref selectIndex)
if ubound(urlData) <> ubound(countData) then
redim countData(ubound(urlData))
end if
randomize
'(ubound(urlData) + 1)得到总元素数
'保证各个链接几率相同
'   0-1
'   1-2
'   2-3
'   3-4
selectIndex = rnd() * (ubound(urlData) + 1)
'修复进制
'    -0.5-0.5 = 0
'    0.5-1.5 = 1
'    1.5-2.5 = 2
'    2.5-3.5 = 3
selectIndex = cLng(selectIndex - 0.5)
countData(selectIndex) = countData(selectIndex) + 1
getRandomLink = urlData(selectIndex)
end function

'测试1000次
do while i < 1000
%><a href="<% =getRandomLink(index) %>">Links_<% =index %></a>&nbsp;
<%
i = i + 1
loop
%><hr />
<%
for i = 0 to ubound(countData)
%><b>Links_<% =i %>：</b><i><% =countData(i) %></i>&nbsp;
<%
next
%>``````

``````<%
'定义URL数据
dim urlData(4)
urlData(0) = "http://www.baidu.com/"
urlData(1) = "http://www.alibaba.com/"
urlData(2) = "http://www.qq.com/"
urlData(3) = "http://www.taobao.com/"

'下面都是一样的代码
dim countData()
redim countData(0)

function getRandomLink(byref selectIndex)
if ubound(urlData) <> ubound(countData) then
redim countData(ubound(urlData))
end if
randomize
'(ubound(urlData) + 1)得到总元素数
'保证各个链接几率相同
'   0-1
'   1-2
'   2-3
'   3-4
selectIndex = rnd() * (ubound(urlData) + 1)
'修复进制
'    -0.5-0.5 = 0
'    0.5-1.5 = 1
'    1.5-2.5 = 2
'    2.5-3.5 = 3
selectIndex = cLng(selectIndex - 0.5)
countData(selectIndex) = countData(selectIndex) + 1
getRandomLink = urlData(selectIndex)
end function

'测试1000次
do while i < 1000
%><a href="<% =getRandomLink(index) %>">Links_<% =index %></a>&nbsp;
<%
i = i + 1
loop
%><hr />
<%
for i = 0 to ubound(countData)
%><b>Links_<% =i %>：</b><i><% =countData(i) %></i>&nbsp;
<%
next
%>``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进