2016-12-05 279 views
-1

我有JavaScript代碼來計算按鈕點擊次數。但是重新加載頁面時,計數器設置爲零。Javascript函數計數按鈕點擊?

是否有任何解決方案來計算按鈕點擊,並在頁面重新加載時保持該變量值?

var count = 0; 
 
var button = document.getElementById("countButton"); 
 
var display = document.getElementById("displayCount"); 
 
// Line commented out as SO does not allow it 
 
// window.localStorage.setItem("on_load_counter", count); 
 
button.onclick = function() { 
 
    count++; 
 
    display.innerHTML = count; 
 
}
<input type="button" value="Count" id="countButton" /> 
 
<p>The button was pressed <span id="displayCount">0</span> times.</p>

+2

使用[Web存儲API(https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) – Satpal

+1

可以節省櫃檯在餅乾或HTML5存儲\ –

+1

利用會話存儲或本地存儲的那個Satpal是正確的 – Jigar7521

回答

0

這是所有ü需要:d

var count = localStorage.on_load_counter || 0; 
    var button = document.getElementById("countButton"); 
    var display = document.getElementById("displayCount"); 

    button.onclick = function(){ 
    localStorage.on_load_counter = display.innerHTML = ++count; 
    } 
0

使用變量localStorage.clickcount,你可以每次點擊都遞增。

看到這個jsfiddle

-1

修補它與我的一些DataSave API和它的工作原理,在這裏你去!

<body onload="loadStats();"> 
<input type="button" value="Count" id="countButton" /> 
<p>The button was pressed <span id="displayCount">0</span> times.</p> 

<script type="text/javascript"> 
var count = 0; 
var button = document.getElementById("countButton"); 
var display = document.getElementById("displayCount"); 
function loadStats(){ 
if(window.localStorage.getItem('count')){ 
count = window.localStorage.getItem('count') 
display.innerHTML = count; 
} else { 
window.localStorage.setItem('count', 0) 
} //Checks if data has been saved before so Count value doesnt become null. 
} 
window.localStorage.setItem("on_load_counter", count); 
button.onclick = function(){ 
count++; 
window.localStorage.setItem("count", count) 
display.innerHTML = count; 
} 
</script> 
</body> 
+0

嗨這個代碼現在工作。但現在的問題是它在我的博客上無法正常工作。不同PC計數器的意義從零開始。我想在我的博客上訪問這個。 –