我正在尝试将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页开始。对于什么是错误的任何建议?
答案 0 :(得分:1)
不是拥有访问过的页面列表,而是拥有一个列表,列出每次点击时随机拼接的所有页面。没有完成页面的示例:
var pages = JSON.parse(localStorage.getItem("pages"));
if (pages === null) {
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'];
}
function onClick () {
var randomIdx = Math.floor(Math.random() * pages.length),
page = pages[randomIdx];
pages.splice(randomIdx, 0);
localStorage.setItem("pages", JSON.stringify(pages));
window.location.href = page;
}