随机麻木显示随机链接

时间:2014-09-26 11:22:08

标签: javascript html arrays random floor

我正在制作一个显示随机链接的页面。在JavaScript代码中,它包含一系列链接,如果用户未启用Java,则会自动设置指向YouTube的链接。这只是我被分配的练习,只是让你知道。目前,没有链接出现。

HTML:

<html>
<head>
<title>Working with Randoms</title>
</head>
<body>
<script type="text/javascript" src="random.js"></script>
<h1>Random Link</h1>
<div id="random_link"></div>
</body>
</html>

JavaScript的:

var jsEnabled = navigator.javaEnabled();
var rand_link = document.getElementById("random_link");

if(jsEnabled=false;){
rand_link.innerHTML = "<a href="www.youtube.com">Default Link</a>";}

var link = new Array(5);
link[0]="http://www.pageresource.com";
link[1]="http://www.javascriptcity.com;"
link[2]="http://www.mydemos.com";
link[3]="http://www.yahoo.com";
link[4]="http://www.google.com";

var rand_int = Math.floor(Math.random()*5);

rand_link.innerHTML = "<a href="+link[rand_int]+">Random Link!</a>"

2 个答案:

答案 0 :(得分:0)

错字。

替换:

link[1]="http://www.javascriptcity.com;"

使用:

link[1]="http://www.javascriptcity.com";
//                                    ^ 

并替换:

if(jsEnabled=false;){

使用:

if(jsEnabled == false){
//           ^ `==` means "equals", A single `=` is an assignment.
// Also, no `;` in `if` statements.

最后:

rand_link.innerHTML = "<a href="www.youtube.com">Default Link</a>";}

使用:

rand_link.innerHTML = "<a href=\"www.youtube.com\">Default Link</a>";}
//                             ^ Escape quotes in a string

答案 1 :(得分:0)

这是另一种解决方案

var jsEnabled = navigator.javaEnabled();
var rand_link = document.getElementById("random_link");

// You had a Typo in the if sytaxt
if(jsEnabled==false){
    rand_link.innerHTML = '<a href="www.youtube.com">Default Link</a>';
}

var link = new Array();
link[0]="http://www.pageresource.com";
link[1]="http://www.javascriptcity.com;"
link[2]="http://www.mydemos.com";
link[3]="http://www.yahoo.com";
link[4]="http://www.google.com";

// The math.random returns a value form 0 to 1. The returned value is a float, 
// and you need a int to access an element in an array. You need to add modulo 
// 5 to the solution. Wich gives you a value between 0 to 4 
var rand_int = Math.floor(Math.random()*100)%5;

rand_link.innerHTML = "<a href="+link[rand_int]+">Random Link!</a>"

JsFiddle:http://jsfiddle.net/gvLLuv8y/