javaScript --- 解决(webview/微信浏览器/页面刷新/页面后退/URL重置页面刷新)AJAX页数重置问题

效果如下:

这里写图片描述

页数的数据可以根据localStorage.test的值作为页数值进行获取

代码如下:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        .box {
            width: 60px;
            height: 35px;
            display: flex;
        }
        .box div {
            flex: 1;
            text-align: center;
            line-height: 35px;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="add">+</div>
        <div class="value"></div>
        <div class="remove">-</div>
    </div>

    <a href="https://blog.csdn.net/sinat_19327991">跳转新页面</a>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">

        //History 对象包含用户(在浏览器窗口中)访问过的 URL。
        var historyObj = window.history;

        //historyObj.length 返回浏览器历史列表中的 URL 数量。
        //根据historyObj.length 的数量判断是否是第一次进入此页面
        if (historyObj.length == 1) {
            localStorage.test = 1;
            $('.value').text(localStorage.test)
        } else {
            $('.value').text(localStorage.test)
        }

        $('.add').click(function(){
            localStorage.test++;
            $('.value').text(localStorage.test);
        })

        $('.remove').click(function(){
            localStorage.test--;
            $('.value').text(localStorage.test);
        })

        /*
         *  点击某个离开页面的链接
         *  在地址栏中键入了新的 URL
         *  使用前进或后退按钮
         *  关闭浏览器
         *  重新加载页面
         *  满足以上条件都触发此事件
         */
        $(window).unload(function(){
            if (historyObj.length == 1) {
                localStorage.test = 1;
            }
        })
    </script>
</body>
</html>
发布了102 篇原创文章 · 获赞 75 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/sinat_19327991/article/details/81383576