2017-07-14 99 views
0

這是我的代碼:如何永久保存我的鏈接點擊次數?

<script type="text/javascript"> 
 
var clicks = 0; 
 
function onClick() { 
 
    clicks += 1; 
 
    document.getElementById("clicks").innerHTML = clicks; 
 
}; 
 
</script> 
 

 
<center> 
 
<button type="button" style="height: 40px; width: 200px" onClick="onClick()"> 
 
<a href="url">DOWNLOAD</a> 
 
</button> 
 
<p>Downloaded: <a id="clicks">0</a></p> 
 
</center>

+0

您好,歡迎堆棧溢出,請花時間去通過[歡迎參觀(https://stackoverflow.com/tour)瞭解你在這裏的方式(並獲得你的第一個徽章),閱讀如何創建[mcve]示例,並檢查[問],以便增加獲得反饋和有用答案的機會。 – garfbradaz

回答

0

,如果你想保持它在你的瀏覽器中的數據閱讀餅乾localStorage的

+0

我想保持它在MySQL服務器 – Kgopotso

+1

這是一個評論。一個20k用戶應該知道 –

+0

不幸的是,這是一個舍入錯誤,我只在19.988。我還有很多要學習。 – cweiske

1

以下是您想要使用SessionStorage的示例。即使刷新頁面,點擊計數器也會持續存在。

另外,在每次點擊時,您都可以將其存儲在服務器上。

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script> 
 
function clickCounter() { 
 
    if(typeof(Storage) !== "undefined") { 
 
     if (sessionStorage.clickcount) { 
 
      sessionStorage.clickcount = Number(sessionStorage.clickcount)+1; 
 
     } else { 
 
      sessionStorage.clickcount = 1; 
 
     } 
 
     document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session."; 
 
    } else { 
 
     document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage..."; 
 
    } 
 
} 
 
</script> 
 
</head> 
 
<body> 
 
<p><button onclick="clickCounter()" type="button">Click me!</button></p> 
 
<div id="result"></div> 
 
<p>Click the button to see the counter increase.</p> 
 
<p>Close the browser tab (or window), and try again, and the counter is reset.</p> 
 
</body> 
 
</html>

您還可以使用localStorage的這種情況。本地存儲更安全,大量數據可以存儲在本地,而不會影響網站性能。

與Cookie不同,存儲限制要大得多(至少5MB),並且信息永遠不會傳輸到服務器。

下面是一個例子

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script> 
 
function clickCounter() { 
 
    if(typeof(Storage) !== "undefined") { 
 
     if (localStorage.clickcount) { 
 
      localStorage.clickcount = Number(localStorage.clickcount)+1; 
 
     } else { 
 
      localStorage.clickcount = 1; 
 
     } 
 
     document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s)."; 
 
    } else { 
 
     document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage..."; 
 
    } 
 
} 
 
</script> 
 
</head> 
 
<body> 
 
<p><button onclick="clickCounter()" type="button">Click me!</button></p> 
 
<div id="result"></div> 
 
<p>Click the button to see the counter increase.</p> 
 
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p> 
 
</body> 
 
</html>

+0

@Jonasw:謝謝!我同意 !。 也包含localStorage的片段。以防萬一它能幫助某人在一個地方找到並比較兩個例子。 –

+0

我不知道編碼這麼多,我只是想爲這個按鈕做一個簡單的下載計數:

Kgopotso

+0

我只是希望每個按鈕點擊以存儲在我的服務器上(按鈕指的是鏈接)

Kgopotso