[英]How can I count the number of the visitors on my website using JavaScript?
I need a counter to integrate inside my HTML code that counts from one to three when the visitors visited my webpage. 我需要一个计数器来集成到我的HTML代码中,当访问者访问我的网页时,该计数器从一到三。
For example if the first visitor visited my page it count to 1, then the next visitor visited the page it count to 2, and for the 3rd visitor count to 3, then for the 4th visitor again starts from 1 and so on. 例如,如果第一个访问者访问了我的页面,它的计数为1,那么下一个访问者访问了它的页面计数为2,对于第3个访问者,计数为3,那么第4个访问者再次从1开始,依此类推。
You could use a cookie and simply update the cookie count detected when the user refreshes, or with a timer. 您可以使用cookie并仅在用户刷新时或使用计时器来更新检测到的cookie计数。 You could also do different things once you have the cookie. 拥有Cookie后,您还可以做其他事情。 You could also take advantage of localstorage. 您还可以利用本地存储。
Check out - http://samy.pl/evercookie/ 检出-http: //samy.pl/evercookie/
<script type="text/javascript" src="evercookie.js"></script>
<script>
var ec = new evercookie();
// set a cookie "id" to "12345"
// usage: ec.set(key, value)
ec.set("id", "12345");
// retrieve a cookie called "id" (simply)
ec.get("id", function(value) { alert("Cookie value is " + value) });
// or use a more advanced callback function for getting our cookie
// the cookie value is the first param
// an object containing the different storage methods
// and returned cookie values is the second parameter
function getCookie(best_candidate, all_candidates)
{
alert("The retrieved cookie is: " + best_candidate + "\n" +
"You can see what each storage mechanism returned " +
"by looping through the all_candidates object.");
for (var item in all_candidates)
document.write("Storage mechanism " + item +
" returned: " + all_candidates[item] + "<br>");
}
ec.get("id", getCookie);
// we look for "candidates" based off the number of "cookies" that
// come back matching since it's possible for mismatching cookies.
// the best candidate is most likely the correct one
</script>
As indicated in the comments, if you are just looking for some method of loading random pages with equal probability, without more complicated server-side code, you could do something like this: 如注释中所示,如果您只是在寻找一种以相同的概率加载随机页面的方法,而无需更复杂的服务器端代码,则可以执行以下操作:
<script type="text/javascript">
window.onload = function() {
var numberOfPages = 3;
var num = Math.round(Math.random() * numberOfPages);
window.location.href = "/" + num + ".html";
};
</script>
Of course, then you would have pages 0.html
, 1.html
, and 2.html
. 当然,那么你将有网页0.html
, 1.html
和2.html
。 This will randomly load one of these three pages with equal probability. 这将以相等的概率随机加载这三个页面之一。 It can also be extended to as many pages as you wish, just add more pages and increase the numberOfPages
variable. 它也可以扩展到任意数量的页面,只需添加更多页面并增加numberOfPages
变量即可。 This should work if you put this script within your site's index--the rest of the page can be empty. 如果将此脚本放在网站的索引中,则此方法应该起作用-页面的其余部分可以为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.