我有这个代码,它会计算按钮上的点击次数。 但它只显示点击按钮后的点击次数。
即使您没有点击按钮,我也需要及时显示点击次数。
<html>
<head>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("clicks").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
} else {
document.getElementById("clicks").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="clicks"></div>
</body>
我希望有人可以帮助我。
答案 0 :(得分:4)
您只需要在DOMContentLoaded
事件
document.addEventListener( "DOMContentLoaded", function(){
var clickCount = localStorage.clickcount || 0;
document.getElementById("clicks").innerHTML = "You have clicked the button " + clickCount + " time(s).";
});
只需在script
标记
答案 1 :(得分:0)
var hasLocalStorage = false;
document.addEventListener("DOMContentLoaded", function() {
var element = document.getElementById("clicks");
if (typeof(Storage) !== "undefined") {
var clicks = localStorage.clickcount || 0;
hasLocalStorage = true;
updateMessage(element, clicks);
}
document.getElementById('clicker').addEventListener('click', function() {
var clicks;
if (hasLocalStorage && localStorage.clickcount) {
clicks = Number(localStorage.clickcount) + 1;
}
updateMessage(element, clicks);
});
});
function updateMessage(element, clicks) {
if (!element) {
return;
}
var message = "Sorry, your browser does not support web storage...";
if (clicks >= 0) {
message = "You have clicked the button " + clicks + " time(s).";
localStorage.clickcount = clicks;
}
element.innerHTML = message;
}
&#13;
<p>
<button id="clicker" type="button">Click me!</button>
</p>
<div id="clicks"></div>
&#13;