How to count clicks with javascript?

后端 未结 8 2247
予麋鹿
予麋鹿 2020-12-01 22:14

Can I count clicks on links with javascript?

8条回答
  •  误落风尘
    2020-12-01 22:54

    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

    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.

提交回复
热议问题