2014-01-14 25 views
0

我有一個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]; 

(因爲這似乎是這樣一個簡單的請求,我擔心我會在這裏用餐還活着,我會跟進:是的,我用Google搜索,但無法找到答案,這是有道理的,以我的非-js精通大腦。有很多如何循環上點擊或頁面刷新隨機更新......但不知道如何循環在頁面刷新)

http://jsfiddle.net/pixeloco/Ma2VA/

回答

0

你可以做到這一點使用本地存儲。這是基於會話的。 (這意味着它不會消失,直到瀏覽器關閉)。

您可以使用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>