通过Javascript/HTML生成随机链接
我正在尝试创建一个脚本,该脚本允许我显示将用户重定向到四个站点中选定的随机URL的超链接。到目前为止,我已经为网站创建了一个数组,并且尝试生成随机url。为了我的目的,输出(“点击去一个随机站点”)不是一个按钮,而是一个简单的(可点击的)字符串。通过Javascript/HTML生成随机链接
运行代码时,我得到一个参考错误“未定义链接(在第18行)”。我认为我已经在代码中定义了链接var link = 'http://' + links[randIdx];
,所以我不完全确定为什么我得到这个错误以及如何解决它。
任何人都可以看看我的代码,看看我犯了什么错误,以及如何修复它?
<a href="javascript:openSite()">Click to go to a random site</a>
<script>
function openSite() {
var links = [
"google.com",
"youtube.com",
"reddit.com",
"apple.com"]
openSite = function() {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'http://' + links[randIdx];
};
return link;
document.getElementById("link").innerHTML = openSite();
}
</script>
<a href="javascript:openSite()">Click to go to a random site</a>
<script>
var links = [
"google.com",
"youtube.com",
"reddit.com",
"apple.com"]
var openSite = function() {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'http://' + links[randIdx];
return link;
};
</script>
对我来说,ManoDestra的答案奏效了,而这个并没有! –
@KatinkaHesselink我认为你是对的。我的答案可能无法正常工作。 Manodestra的答案照原样。 –
下面是代码:
var links = [
"google.com",
"youtube.com",
"reddit.com",
"apple.com"]
function openSite() {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'http://' + links[randIdx];
return link;
};
document.getElementById("link").innerHTML = openSite();
这里有一个简单的方法来做到这一点。
<script>
var sites = [
'http://www.google.com',
'http://www.stackoverflow.com',
'http://www.example.com',
'http://www.youtube.com'
];
function randomSite() {
var i = parseInt(Math.random() * sites.length);
location.href = sites[i];
}
</script>
<a href="#" onclick="randomSite();">Random</a>
为什么openSite()函数里面还有openSite()函数? –
这可能是我使用不同的方法让代码工作的一个副产品 –