这是我的代码:
<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 :(得分: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>
&#13;
在这种情况下,您也可以使用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>
&#13;
答案 1 :(得分:0)
如果您想在浏览器中保留数据,请阅读 cookies 或 localstorage 。