代码改变世界

在 Javascript 端利用 windows.location.hash 来路由的简单示例

2021-04-28 21:44  音乐让我说  阅读(323)  评论(0编辑  收藏  举报

直接贴代码了:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body class="layui-layout-body">
    <div id="mainContent"> </div> 
    <input type="button" value="点击试试" onclick="getHtmlFromServer()" />
    <script>
        var i = 1;
        var cachedObj = new Object();
        function getHtmlFromServer() {
            setContentToDiv("正在请求服务器,请稍后...");
            $.ajax({
                url: "/",
                data: {},
                dataType: "html",
                type: "GET",
                async: true,
                success: function (data, status)
                {
                    eval("cachedObj['" + i + "']=" + i + ";");
                    location.hash = "#" + i;
                    setContentToDiv(i);
                    ++i;
                },
                error: function (xmlHttpRequest, errorInfo)
                {

                }
            });
        }

        function setContentToDiv(content) {
            document.getElementById("mainContent").innerHTML = content;
        }

        function onhashchangeCore() {
            //alert("开始执行 window.onhashchange 事件!"); 
            var hashStr = location.hash.replace("#", "");
            if (hashStr == "") {
                //alert("检测到获取的 location.hash 等于空,忽略处理。"); 
                return;
            }
            if (isNaN(hashStr)) {
                //非数字,忽略处理 
                return;
            }
            var hashInt = parseInt(hashStr, 10);
            if (hashInt <= 0) {
                //小于或等于0,忽略处理 return; 
            }
            var execResult = eval("cachedObj['" + hashInt + "']");
            if (typeof (execResult) == "undefined") {
                //alert("系统缓存中没有值!"); 
                i = hashInt;
                getHtmlFromServer();
                return;
            }
            setContentToDiv(execResult);
        }
        if (typeof (window.onhashchange) != "undefined") {
            window.onhashchange = function () {
                onhashchangeCore();
            }
        }
        else {
            //alert("您使用的浏览器太老,不支持 window.onhashchange 事件,可能系统无法完美呈现!");
        }

    </script>
</body>
</html>

 

谢谢浏览!