当我按下按钮时,我正在尝试创建一个网站,随机选择一个网页(我有35个)。但是我希望它只能访问每个站点一次。我认为cookie可以完成这项工作,但我不确定该怎么做。 所以我想让饼干记住哪些页面已被访问过哪些页面已被访问过。 我是一个很新的JavaScript,所以请你好。
我的JavaScript:
function myFunction() {
var tal=Math.floor((Math.random() * 35) + 1)
window.location.href = "Sang"+tal+".html";
}
我的一个网页:
<!DOCTYPE html>
<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="pokemon.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> World we must defend </li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Pokemon theme</li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Gotta Catch 'em All<li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> You teach me i teach you <li>
</button>
</ul>
</div>
</div>
<p id="Test"></p>
</body>
</html>
答案 0 :(得分:0)
取自https://stackoverflow.com/a/24103596/1029988
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
您可以使用这两个来设置和读取访问过的页面数组:
function myFunction() {
var cookie = readCookie('pages') || '';
var pages = cookie.split(',');
var tal=Math.floor((Math.random() * 35) + 1);
while (pages.indexOf(tal) > -1) { // randomize until you reach a number not stored in the cookie
tal=Math.floor((Math.random() * 35) + 1);
}
window.location.href = "Sang"+tal+".html";
pages.push(tal);
createCookie('pages', pages.join(','))
}
但是,while循环可能需要一些时间才能执行,特别是在35个可能页面的末尾(即只剩下5个数字时)。您可以通过从选项列表中删除存储的数字来提高代码效率:
function myFunction() {
var cookie = readCookie('pages') || '';
var pages = cookie.split(',');
var available_choices = [];
for (var i = 1; i < 36; i++) {
if (pages.indexOf('' + i) == -1) {
available_choices.push(i);
}
}
var tal=available_choices[Math.floor(Math.random() * available_choices.length - 1)];
window.location.href = "Sang"+tal+".html";
pages.push(tal);
createCookie('pages', pages.join(','))
}