我正在编写代码,生成一个随机链接,从文本字段添加到另一个其他链接,如下所示:
http://{generated link}/{link entered in a text field}
我试过这个,但不适合我;我不知道错误。
<SCRIPT Language="Javascript">
function Randomlink()
{
Url = new Array;
Url[0] = "http://www.google.com";
Url[1] = "http://www.youtube.com";
Url[2] = "http://www.facebook.com";
Url[3] = "http://www.yahoo.com";
Chooselink = Math.round(Math.random() * (Url.length+1));
}
</SCRIPT>
<center>
<input id="input" name="url" onfocus="this.value='' type="text" value="Type url here.." />
<input onclick="window.open(###randomize link here###+ window.document.getElementById('input').value.replace(/^https?:\/\//,''))" style="font-family: Arial, sans-serif; font-size: 0.9em; margin: 2px 0; padding: 4px; width: 100px;" type="button" value="Go"/>
</center>
答案 0 :(得分:0)
如果你把我的评论放在一起,它看起来像这样:
<head>
⋮
<!-- external stylesheet, because it’s good practice -->
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<form id="search">
<!-- placeholder, because it’s semantically correct,
good-looking, and not annoying -->
<input type="url" name="q" placeholder="Type a URL here" />
<!-- submit button, because it’s semantically correct,
and usable through Enter for free -->
<input type="submit" id="go" value="Go" />
</form>
<!-- external script, because it’s good practice -->
<script type="text/javascript" src="script.js"></script>
</body>
#search {
text-align: center;
}
#go {
font-family: Arial, sans-serif;
font-size: 0.9em;
margin: 2px 0;
padding: 4px;
width: 100px;
}
"use strict";
// A more generic function to pick a random element from an array (or array-like)
function randomChoice(list) {
// | 0 truncates the result to a 32-bit integer
return list[Math.random() * list.length | 0];
}
// Set the action for the search form; this isn’t quite correct yet
var search = document.getElementById("search");
search.action = randomChoice([
"https://www.google.com/",
"https://www.youtube.com/",
"https://www.facebook.com/",
"https://www.yahoo.com/"
]);
这可能不完全是你所追求的,但它是一个更好的起点。
答案 1 :(得分:0)
我稍微修改了你的代码,它按预期工作:
JS在此处更改:返回网址
修改后的代码
<SCRIPT Language="Javascript">
function Randomlink()
{
Url = new Array;
Url[0] = "http://www.google.com";
Url[1] = "http://www.youtube.com";
Url[2] = "http://www.facebook.com";
Url[3] = "http://www.yahoo.com";
return Url[Math.floor(Math.random() * Url.length)];
}
</SCRIPT>
HTML更改在此处: window.open随机链接...
修改后的代码
<center>
<input id="input" name="url" onfocus="this.value=''" type="text" value="Type url here.." />
<input onclick="window.open(Randomlink()+'/'+ window.document.getElementById('input').value.replace(/^https?:\/\//,''))" style="font-family: Arial, sans-serif; font-size: 0.9em; margin: 2px 0; padding: 4px; width: 100px;" type="button" value="Go"/>
</center>
干杯