我有一个div,其文本在页面刷新时随机更新,但我需要的是文本按照其列出的顺序循环,而不是每次页面重新加载时。
var myFact = new Array();
myFact[0] = "I have a dog";
myFact[1] = "My favorite sport is hockey";
myFact[2] = "I like chocolate";
myFact[3] = "Orange is my favorite color";
var myRandom = Math.floor(Math.random()*myFact.length);
document.getElementById('myFact').innerHTML= myFact[myRandom];
(因为这似乎是一个如此简单的请求,我担心我会在这里被活着吃掉,我会跟进:是的,我用谷歌搜索了它但找不到对我的非js精通有意义的答案大脑。有很多关于如何循环浏览点击或在页面刷新时随机更新...但不是如何循环浏览页面刷新)
答案 0 :(得分:0)
您可以使用localStorage完成此操作。这是基于会话的。 (意思是在浏览器关闭之前它不会消失)。
您可以将localStorage对象用作存储桶,以便在刷新后放置要保留的变量。
<div id="myFact"></div>
<script>
if (typeof(Storage) !== undefined) {
var myFact = new Array();
myFact[0] = "I have a dog";
myFact[1] = "My favorite sport is hockey";
myFact[2] = "I like chocolate";
myFact[3] = "Orange is my favorite color";
//var myRandom = Math.floor(Math.random()*myFact.length);
if (!localStorage.factIndex) {
localStorage.factIndex = 0;
} else {
localStorage.factIndex = (localStorage.factIndex >= (myFact.length-1)) ? 0: parseInt(localStorage.factIndex)+1;
}
document.getElementById('myFact').innerHTML = myFact[localStorage.factIndex];
} else {
//LocalStorage not supported with this browser
}
</script>