通过Javascript/HTML生成随机链接 [英] Generating a random link through Javascript/HTML
问题描述
我正在尝试创建一个脚本,该脚本允许我显示一个超链接,该超链接将用户重定向到从四个站点中选择的随机URL.到目前为止,我已经为站点创建了一个数组,并创建了一个试图生成随机URL的函数.对我而言,重要的是输出(单击以转到随机站点")不是按钮,而是简单的(可单击的)字符串.
I am trying to create a script that allows me to display a hyperlink that redirects the user to a random url selected out of four sites. So far I have created an array for the sites, and a function that attempts to generate the random url. For my purpose it is important for the output ("Click to go to a random site") is not a button, but a simple (clickable) string.
运行代码时,出现参考错误未定义链接(第18行)".我以为我已经在代码中用var link = 'http://' + links[randIdx];
定义了链接,所以我不完全确定为什么会收到此错误以及如何解决该错误.
When running the code I get a reference error "link is not defined (on line 18)". I thought that I had defined link in the code with var link = 'http://' + links[randIdx];
, so I am not entirely sure why I am getting this error and how to fix it.
任何可以查看我的代码的人,看看我在哪里犯了错误以及如何解决它?
Anyone that could take a look at my code to see where I have made a mistake and how I could fix it?
<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>
这篇关于通过Javascript/HTML生成随机链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!