2017-07-14 101 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