Total amount of times a link is clicked

2019-09-09 15:38发布

Okay so I have a link that is directed to one website example:

<a href="https://www.google.com">Click me!</a>

So what I want to chnage the href link after the 10th time that is clicked to a different location what ive done is flawed becase it only counts the number of times the link has been clicked since the last reload ex:

var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});

So i need a counter that keeps track of the total times its been clicked not just the times after the page reloads. It needs to keep track of every click from every user because so i dont think cookies would work i may be wrong.

2条回答
孤傲高冷的网名
2楼-- · 2019-09-09 15:44

Using a cookie you can save the state and later read it and use it.

With jQuery it is very easy to use cookies.

 $.cookie("var", "10");
查看更多
beautiful°
3楼-- · 2019-09-09 16:03

You need to preserve the value in a cookie/local storage to retain the value across multiple sessions. You can use a library like jQuery cookie to make the cookie operations easy

Ex:

$(document).ready(function () {
    $('a').click(function () {
        var count = parseInt($.cookie('link-count'), 10) || 0
        count++;
        if (count > 10) {
            $('a').attr("href", "https://www.yahoo.com");
        }
        $.cookie('link-count', count)
    });
});

Demo: Fiddle - click on the link and refresh the page the counter will retain the value

查看更多
登录 后发表回答