A gerar uma ligação aleatória através do Javascript / HTML
Estou a tentar criar um programa que me permite mostrar uma hiperligação que redirecciona o utilizador para uma url aleatória seleccionada de quatro sítios. Até agora eu criei um array para os sites, e uma função que tenta gerar a url aleatória. Para minha finalidade é importante para a saída ("Clique para ir a um site Aleatório") não é um botão, mas uma cadeia simples (clickable).
ao executar o código eu recebo um erro de referência " link não está definido (na linha 18)". I pensei que eu tinha definido link no código com var link = 'http://' + links[randIdx];
, Então eu não estou inteiramente certo por que eu estou recebendo esse erro e como corrigi-lo.
<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>
0
3 answers
<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>
2
Author: Mohit Bhardwaj, 2016-06-10 15:22:44
Eis uma forma simples de o fazer.
<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>
3
Author: ManoDestra, 2016-06-10 15:30:47
Aqui está o código:
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();
Aqui está o violino. https://jsfiddle.net/gerardofurtado/90vycqyy/1/
0
Author: Gerardo Furtado, 2016-06-10 15:29:08