0
我想鏈接35個網頁與math.random。不過,我不希望它多次訪問每個網站。所以我有這樣的:隨機更改網頁而沒有獲得相同的頁面兩次
function myFunction() {
var pages = ['sang1.html', 'sang2.html', 'sang3.html', 'sang4.html', 'sang5.html', 'sang6.html', 'sang7.html', 'sang8.html', 'sang9.html', 'sang10.html', 'sang11.html', 'sang12.html', 'sang13.html', 'sang14.html', 'sang15.html', 'sang17.html', 'sang18.html', 'sang19.html', 'sang20.html', 'sang21.html'];
var page, visitedPages = JSON.parse(localStorage.getItem("visitedPages"));
if (visitedPages === null) {
visitedPages = [];
}
if (pages.length !== visitedPages.length) {
for (var i = 0; i < pages.length; i++) {
page = pages[Math.floor((Math.random() * pages.length) + 1)];
if (visitedPages.indexOf(page) === -1) { //unvisited yet
localStorage.setItem("visitedPages", JSON.stringify(visitedPages.push(page)));
window.location.href = page;
break;
}
}
} else {window.location.href = score.html //All pages visited at once
}
}
隨機頁面:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Gæt en sang</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="Test.js"></script>
</head>
<body>
<audio class="hidden" controls autoplay>
<source src="horse.ogg" type="audio/ogg">
<source src="Original GhostBusters Theme Song.mp3" type="audio/mpeg">
</audio>
<div id="header">
<h2> Gæt sangen og hejs flagstangen!</h2>
</div>
<div id="left">
<ul> Hvilken sang er dette?
</br>
<button type="button" onclick="myFunction()">
<li> Ghost busters</li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Poltergeist</li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Something strange<li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Who are you gonna call<li>
</button>
</ul>
</div>
</div>
<p id="Test"></p>
</body>
</html>
讓我有你按下一個按鈕,然後它開始myfunction的。這適用於我所有的網站。但是,當我按下我的按鈕時,它總是轉到第2頁。並且僅從第1頁開始。對於什麼是錯誤的任何建議?
我認爲這將是一個範圍問題。在'function'之外定義'page,visitedPages'來創建'global'。 – vaso123 2014-10-20 11:26:10
但我想這是一個更好的解決方案,如果你只是從數組中刪除已經訪問過的頁面,如果你不想用'visitedPages'數組做任何事情。 – vaso123 2014-10-20 11:27:30
它似乎仍然不起作用 – thegamingbookworm 2014-10-20 11:35:31