Total amount of times a link is clicked

删除回忆录丶 提交于 2019-12-11 21:20:31

问题


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.


回答1:


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




回答2:


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");


来源:https://stackoverflow.com/questions/18479019/total-amount-of-times-a-link-is-clicked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!