嗨,我試圖找到一種使用本地存盤來保存高分的方法,我有一個簡單的腳本,可以在每次用戶播放時設定分數。
localStorage.score = $(".score").text();
$(".highscore").text(localStorage.score);
但是,我現在想對其進行擴展,如果它是一個新的高分,它只會更新分數,并設定它達到的日期。謝謝
uj5u.com熱心網友回復:
您需要知道要將存盤放在哪里,在一個單獨的存盤專案中,或者將其更改為一個物件并添加將包含分數和日期的值。
然后在使用 localStorage 時,要正確插入 JS物件,必須將其轉換為 JSON: JSON.stringify(),然后在檢索時決議它:JSON.parse()
這是一個作業示例:
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="score">35</div>
<div class="highscore"></div>
<div class="highscore-date"></div>
JS:
$(function() {
let date = new Date();
localStorage.score =
localStorage.score ?
Number($(".score").text()) > JSON.parse(localStorage.score).score ?
JSON.stringify({
"score": $(".score").text(),
"date": `${date.toDateString()} at ${date.toLocaleTimeString()}`
})
: localStorage.score
: JSON.stringify({
"score": $(".score").text(),
"date": `${date.toDateString()} at ${date.toLocaleTimeString()}`
})
$(".highscore").text(JSON.parse(localStorage.score).score);
$(".highscore-date").text(JSON.parse(localStorage.score).date);
});
此腳本首先檢查是否已在 localStorage 中設定了 score 項。如果存在,則首先將 score 值轉換為 a Number,因為它被讀取為字串,然后檢查它是否大于當前值,并相應更新
這里使用一個物件將分數和日期的值保存在同一個存盤項中
編輯:
JSON.stringify({
"score": JSON.parse(localStorage.score).score,
"date": JSON.parse(localStorage.score).date
})
折射到localStorage.score
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480795.html
上一篇:在AJAX承諾完成之前阻止點擊
