我有一个简单的脚本,该脚本旨在每次单击图像时增加一个计数器:
<script>
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("counter").innerHTML = localStorage.clickcount;
} else {
document.getElementById("counter").innerHTML = "Your browser does not support web storage...";
}
}
</script>
html:
<img id="heart" src="../assets/images/redheart.png" title="Give Love!" onclick="clickCounter()"><p id="counter"></p>
工作正常,但我希望能够在点击之前显示计数。现在,仅在单击图像按钮后计数器才会显示。
感谢您的所有输入。
答案 0 :(得分:0)
如果这不是您想要的,请告诉我。
首先,进行一些调整:
出于可访问性原因:
<img>
设为<button>
(带有背景图片)。按钮超级易于访问且对键盘友好(标签,输入键等)aria-label
,因为它不包含文本内容稍微清理了一下JavaScript。
行为:
在首页加载中……
然后我们执行五次单击,然后刷新页面。
注意:由于编辑器中的安全限制,此演示无法在此处用于Stack Overflow。看看我创建的fiddle。
document.querySelector("button").addEventListener("click", clickCounter);
document.addEventListener("DOMContentLoaded", showValue);
let counter = document.getElementById("counter");
function showValue() {
counter.innerHTML = `Current count = ${localStorage.clickcount || 0}`;
}
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
showValue();
} else {
counter.innerHTML = "Your browser does not support web storage...";
}
}
button {
background-image: url(http://icons.iconarchive.com/icons/benzlee/free-christmas/512/heart-icon.png);
background-repeat: no-repeat;
background-size: 64px 64px;
background-color: transparent;
border: none;
display: inline-block;
width: 64px;
height: 64px;
cursor: pointer;
}
<button title="Give Love!" aria-label="Give Love!">
<div id="counter"></div>