现在我有一个单击按钮(或“喜欢”按钮,它是一个名为 .download png 的图像心脏),它仅在您单击时显示单击按钮结果编号计数器。我试图让按钮一直显示结果,不仅仅是当你点击它时,而且在点击时仍然在计数器上增加一个。这是我目前在标题中的代码:
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.firstButtonCount) {
localStorage.firstButtonCount = Number(localStorage.firstButtonCount)+1;
} else {
localStorage.firstButtonCount = 1;
}
document.getElementById("result").innerHTML = localStorage.firstButtonCount;
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
然后是正文代码:
<p>
<button type="button" onclick="clickCounter()">
<div class="number" id="result"></div>
<img src="download.png" width="50px" height="auto class="clickCounter()" type="button alt="Like"/>
</button>
</p>
我不确定我做错了什么,但如果有人能告诉我如何始终显示结果,那就太棒了!
请注意 :
要获取 localStorage 中的值,请使用 getItem 方法。
要在 localStorage 中添加值,请使用 setItem 方法。
有关更多信息,请参阅本文https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
用下面的代码替换您的代码:
<!DOCTYPE html>
<html lang="pt-br">
<meta charset="utf-8" />
<head>
<title>Vote</title>
</head>
<body>
<p>
<button type="button" onclick="clickCounter()">
<div class="number" id="result"></div>
<img src="https://cdn4.iconfinder.com/data/icons/like-18/32/459-01-512.png" width="50px" height="auto" type="button" alt="Like" />
</button>
</p>
<script type="text/javascript">
var resultElement = document.getElementById('result');
function updateResult() {
resultElement.innerText = parseInt(localStorage.getItem('firstButtonCount')) || 0;;
}
function vote() {
// body...
newCount = parseInt(localStorage.getItem('firstButtonCount')) + 1 || 0 + 1;
localStorage.setItem('firstButtonCount', newCount);
}
function clickCounter() {
if (typeof(Storage) !== "undefined") {
/*
to get a value in localStorage , you use the method getItem
to add a value in localStorage , you use the method setItem
*/
vote();
updateResult();
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
updateResult();
</script>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句