Javascript 如何始终显示单击

Javascript 如何始终显示单击,javascript,Javascript,我有这个代码,它计算点击按钮的次数。 但它仅在您单击按钮后显示单击 <html> <head> <script> function clickCounter() { if(typeof(Storage) !== "undefined") { if (localStorage.clickcount) { localStorage.clickcount = Number(localStorage.clickcount)+1;

我有这个代码,它计算点击按钮的次数。 但它仅在您单击按钮后显示单击

<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>
我需要显示所有的时间点击,即使你没有点击按钮

<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>

函数clickCounter(){
if(类型(存储)!=“未定义”){
if(localStorage.clickcount){
localStorage.clickcount=数字(localStorage.clickcount)+1;
}否则{
localStorage.clickcount=1;
}
document.getElementById(“clicks”).innerHTML=“您已经单击了按钮”+localStorage.clickcount+“time(s)”;
}否则{
document.getElementById(“单击”).innerHTML=“对不起,您的浏览器不支持web存储…”;
}
}
点击我


我希望有人能在这里帮助我。

您只需要在
DOMContentLoaded
事件中调用一个方法

document.addEventListener( "DOMContentLoaded", function(){
  var clickCount = localStorage.clickcount || 0;
  document.getElementById("clicks").innerHTML = "You have clicked the button " + clickCount + " time(s).";
});
只需将此代码添加到
脚本
标记中

var hasLocalStorage=false;
document.addEventListener(“DOMContentLoaded”,function()){
var元素=document.getElementById(“单击”);
if(类型(存储)!=“未定义”){
var clicks=localStorage.clickcount | | 0;
hasLocalStorage=true;
更新消息(元素、单击);
}
document.getElementById('clicker')。addEventListener('click',function(){
var点击;
if(hasLocalStorage&&localStorage.clickcount){
点击次数=数量(localStorage.clickcount)+1;
}
更新消息(元素、单击);
});
});
函数更新消息(元素,单击){
if(!元素){
返回;
}
var message=“对不起,您的浏览器不支持web存储…”;
如果(单击次数>=0){
message=“您已点击按钮”+点击次数+”;
localStorage.clickcount=点击次数;
}
element.innerHTML=消息;
}

点击我!


因此,将函数(clickCounter)附加到正文的onclick事件,而不是按钮的onclick事件。我必须将其放在脚本的何处?我对这一点非常陌生,就像我在回答中提到的——把这段代码放在你已经有的脚本标签中。