【问题标题】:Link click counter, and show how many times link is clicked [duplicate]链接点击计数器,并显示链接被点击的次数[重复]
【发布时间】:2019-01-27 22:19:39
【问题描述】:

我想在点击此链接时计算点击次数。并在 example.com 中显示“点击了多少次(数字)链接” 不要使用mysql。如果没有更好的php,那么javascript就可以了

<a href="http://example.com">example.com</a>

【问题讨论】:

    标签: php html


    【解决方案1】:

    对于纯 JS 实现,您可以使用 localStorage,如下所示:

    <html>
    <script>
        function init() {
            let count = localStorage.getItem('counter');
            if(count === null){
                count = 0;
                localStorage.setItem('counter', count);
            }
            count = parseInt(count);
            updateCount(count);
        }
        function incrementCounter() {
            let count = parseInt(localStorage.getItem('counter'));
            count = count + 1;
            localStorage.setItem('counter', count);
            updateCount(count);
            return true;
        }
        function updateCount(count) {
            document.getElementById("count").innerHTML = "Clicked "+count+" times!";
        }
    </script>
    <body>
        <p id="count">-</p>
        <script type="text/javascript">
            init();
        </script>
        <a href="https://www.google.com" onclick="incrementCounter()">Google</a>
    </body>
    

    【讨论】:

    • 这只会给你一个特定客户的点击次数。不确定OP是否想要那个
    • 哦对了,这样的话,客户端JS就不行了