localStorage

Test1.html:設置數據

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<script>
function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (localStorage.clickcount) {
            localStorage.clickcount = Number(localStorage.clickcount)+1;
			localStorage.setItem("clickCount",localStorage.clickcount);
        } else {
            localStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "你在按鈕上已經點擊了 " + localStorage.clickcount + " 次。";
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
    }
}
</script>
</head>
<body>
<p><button οnclick="clickCounter()" type="button">點我!</button></p>
<div id="result"></div>
<p>點擊按鈕查看數字會自動增加。</p>
<p>關閉瀏覽器,重新打開這個頁面點擊按鈕,可以看到之前的數據是有保留的。</p>
</body>
</html>

如圖點了十五次:

關閉瀏覽器【未清瀏覽器數據的情況下】,打開Test2.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<script>
function clickCounter() {
    if(typeof(Storage) !== "undefined") {
		var clickCount = localStorage.getItem("clickCount");
        document.getElementById("result").innerHTML = "你在按鈕上已經點擊了 " + clickCount + " 次。";
    }
}

</script>
</head>
<body>
<p><button οnclick="clickCounter()" type="button">點我!</button></p>
<div id="result"></div>
</body>
</html>

點擊之後,直接顯示點擊了15次:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章