[英]Saving the number of clicks the user have done in a Button, Storing it in the LocalStorage
我在 HTML、CSS 和 Javascript 中制作了兩個按鈕。第一個按鈕稱為“呼叫按鈕”,第二個按鈕稱為“跳過按鈕”。
過程/場景是:
我已經為上述流程和場景制作了 function。
問題是,每次我單擊“呼叫按鈕”時,頁面都會刷新,並且每次單擊“呼叫按鈕”時按鈕的計數器都會刷新,將其變為零 (0) 值。
現在可以將“計數器”存儲在 LocalStorage 中嗎?
我如何在我的代碼中實現它? 這是我第一次使用這種 function。
我非常感激。
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// Function for counting the number of times the user clicked the call button
let counter = 0;
function enableButton() {
checker += 1;
if(counter === 3){
document.getElementById("button2").disabled = false;
}
}
</script>
</head>
<body>
<button type="button" id="button1" onclick="enableButton()">Call Button</button>
<button type="button" id="button2" disabled>Skip Button</button>
</body>
</html>`
上面的代碼是我工作的一個例子。 但是在我原來的項目中,它有一個刷新/重新加載 function 按鈕。
可能還有其他方法,但這是一個如何將計數器存儲在 localStorage 中的示例:
let counter = localStorage.getItem("clickCounter");
if (counter === null) {
counter = 0;
} else {
counter = parseInt(counter)
}
function enableButton() {
counter += 1;
localStorage.setItem("clickCounter", counter.toString());
if(counter >= 3){
document.getElementById("button2").disabled = false;
}
}
您必須從 localStorage 中解析項目,因為您只能存儲字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.