开发者

Click count possible with javascript?

Let's say, in website, I want to display the notice message block whenever peop开发者_如何学Pythonle click any of the link at my website more than x number of times. Is that possible to count with javascript and display the notice message block ? And can we count the refresh times also ? Or can it be only done with server side language like php ? Please kindly suggest. Thank you.

With Regards,


To do something when any link is clicked is best done with JQuery's live:

Description: Attach a handler to the event for all elements which match the current selector, now and in the future.

$('a').live('click', function() {
// Live handler called.
});

Even if you add more links in run time, this will take care of it.

For counting refreshes I would do it with ajax calls on window.load event, or if you want to use new tech - store it locally with Html5. :-)


You can do that on the client. However, this will be limited to the browser. The simplest will be to store this information in cookies on the client. For instance with jQuery you could simply intercept clicks like that:

$("a").click(function() {
  var clickedUrl = $(this).attr('href');
  // Here you update the cookie for the count of clicks for that A URL
});


I would either count page refreshes serverside or probably call an ajax function to update the count when the page loads.

If you want to count clicks you may need to bind an event to each link and then for each indivisual button store the number of clicks in global variables...


You could register each click event on the document by using:

$(document).click(function()
{

   // Check the number in the cookie and add another
   // click to the cookie

});

Then you could use the jQuery cookie plugin to store that value and check it each time there is a click (in the function above).

here's the cookie plugin: https://github.com/carhartl/jquery-cookie

I threw together a quick example. If you're not worried about doing this from page to page then you don't need cookies, just store it in a variable:

http://www.webdesignandseo.net/jquery/clickcount/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜