Javascript 如何使用javascript计算点击次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5862781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count clicks with javascript?
提问by user719813
Can I count clicks on links with javascript?
我可以用 javascript 计算链接的点击次数吗?
回答by Abdullah Jibaly
You can count clicks within a single request (for example, how many times a button was clicked after the page loaded). You cannot count clicks across requests (after you load another page or reload the current page).
您可以计算单个请求中的点击次数(例如,页面加载后点击按钮的次数)。您无法计算跨请求的点击次数(在加载另一个页面或重新加载当前页面之后)。
Example:
例子:
<script type="text/javascript">var clicks = 0;</script>
<input value="Click" type="button" onclick="clicks++">
UPDATE:
更新:
You can also use the following (using jQuery) to persist it using cookies as recommended by others:
您还可以使用以下(使用 jQuery)来使用其他人推荐的 cookie 来持久化它:
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
回答by Nick Rolando
Sure, add an onclick event handler function to the <a>
tag that retrieves, increments and stores a counter variable. You can retrieve and store this in a hidden field. You will lose the information once you navigate away from the page, however.
当然,将 onclick 事件处理函数<a>
添加到检索、递增和存储计数器变量的标记中。您可以检索并将其存储在隐藏字段中。但是,一旦离开页面,您将丢失信息。
回答by Mathieu Rodic
You can count all clicks on a page's links with this script:
您可以使用此脚本计算页面链接上的所有点击次数:
// This variable contains the number of clicks corresponding to the linked URLs
var clickCount = {}
// List of all a tags
, aList = document.getElementsByTagName('a')
// Function called every time a link is clicked on
, clickCounter = function()
{
clickCount[this.href] = clickCount[this.href] ? clickCount[this.href]+1 : 1;
}
;
// The event is attached to every link having a "href" attribute
for (var i=0 ; i<aList.length, a=aList[i] ; i++)
{
if (this.href)
{
a.onclick = clickCounter;
}
}
// This example uses jQuery to send the data to a PHP script
// A POST request is sent just before the window is closed
onbeforeunload = function()
{
$.post('/tracking.php', clickCount);
}
PS: I don't worry about anchor links, since their tracking may have some interest of its own. If you do, just test if a.href contains location.href+'#' in the for loop.
PS:我不担心锚链接,因为它们的跟踪可能有自己的兴趣。如果这样做,只需在 for 循环中测试 a.href 是否包含 location.href+'#'。
回答by Stephen P
You should count these requests server-side, either straight from the web server logs or from the code that resolves the ?id=1234
to load the actual content.
您应该直接从 Web 服务器日志或从解析?id=1234
加载实际内容的代码中计算服务器端的这些请求。
Don't count requests coming from the page author that you gave the ID to, assuming you have some way to tell (a login, a cookie, an IP address) -- this part would be easier from your code rather than the server logs.
不要计算来自您提供 ID 的页面作者的请求,假设您有某种方法可以告诉(登录名、cookie、IP 地址)——这部分从您的代码而不是服务器日志中会更容易.
回答by user2656482
<script type="text/javascript">
var clicks = 0;
function linkClick() {
document.getElementById('clicked').value = ++clicks;
}
document.write('<a href="#" onclick="linkClick()">Click Me!</a>');
You have clicked the link times.
您已点击链接次数。
回答by vsync
Here's a simple click counter with a limiting factor of 200ms
between clicks. In this exampleI've made it so after 3 subsequent clicks something will happen:
这是一个简单的点击计数器,其限制因素为200ms
点击次数。在这个例子中,我已经做到了,所以在 3 次后续点击后会发生一些事情:
var onClick = (function(){
var count = 0, timer;
return function(){
count++;
clearTimeout(timer);
timer = setTimeout(function(){count = 0}, 200);
// do whatever after 3 clicks
if( count > 2 )
document.body.classList.toggle('mode');
}
})();
document.body.addEventListener("click", onClick);
html, body{ height:100%; }
body{
font:20px Arial;
text-align:center;
padding:20px;
background:#EFDCE8;
transition:.3s;
-moz-user-select:none;
-webkit-user-select:none;
}
body.mode{ background:lightgreen; }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Click anwhere 3 times
</body>
</html>
回答by TayabRaza
I have created a click counter with local storage, so it can store the click counts.
我创建了一个带有本地存储的点击计数器,因此它可以存储点击计数。
<html>
<body>
<a href="#" onclick="clickCounter()">Click Counter</a>
<a href="#" onclick="resetCounter()">Reset Counter</a>
<br>
<p id="result"></p>
<script>
function clickCounter() {
var count = localStorage.clickcount = Number(localStorage.clickcount)+1;
if (isNaN(count) === true) {
count = localStorage.clickcount = 1;
document.getElementById("result").innerHTML = count;
} else {
document.getElementById("result").innerHTML = count;
}
}
function resetCounter() {
var reset = localStorage.clickcount = 0;
document.getElementById("result").innerHTML = reset;
}
</script>
</body>
</html>
回答by RobG
Presumably you are trying to see how many links on a page a user has clicked on in order to see which ones they've visited. That is an unreliable strategy since users can visit links many different ways without clicking on them (context menu, drag to new tab, copy link location, etc.).
大概您正在尝试查看用户点击了页面上的多少链接,以便查看他们访问过哪些链接。这是一种不可靠的策略,因为用户可以通过多种不同方式访问链接而无需单击它们(上下文菜单、拖动到新选项卡、复制链接位置等)。
If you want to know how many links they've clicked on in the current page, the answer is zero since if they click on a link they should go to another page. If you are using a listener to prevent navigation, then the same listener can also count clicks.
如果你想知道他们在当前页面点击了多少链接,答案是零,因为如果他们点击一个链接,他们应该转到另一个页面。如果您使用侦听器来阻止导航,那么同一个侦听器也可以计算点击次数。