利用html锚点来支持浏览器的前进和后退,并加入异步请求

单网页应用如何实现后退和前进操作

  • 本实例实现锚点来支持浏览器的前进和后退

    代码:

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title></title>
    	</head>
    	<body>
    		<div id="menu" style="position: fixed;">
    			<a href="#index">首页</a>
    			<a href="#task">任务</a>
    		</div>
    		<div id="index" style=" 100%;height: 100%;background-color: aqua;text-align: center;vertical-align: middle;font-size: 50px;">我是首页</div>
    		<div id="task" style=" 100%;height: 100%;background-color: aquamarine;text-align: center;vertical-align: middle;font-size: 50px;">我是任务</div>
    	</body>
    	<style type="text/css">
    		*{
    			margin: 0;
    			padding: 0;
    		}
    		html,body{
    			height: 100%;
    		}
    	</style>
    </html>
    
    
  • 本实例实现的是点击连接之后,异步请求后台,拿到数据显示到页面,并且能够实现前进和后台的操作。

    先上代码:

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title></title>
    		<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    	</head>
    	<body style="height: 100%;">
    		<div id="main" style=" position: absolute; 100%;height: 100%;background-color: aliceblue;box-sizing: border-box;">
    			<div style="height: 20%;">
    				<a href="#index" onclick="show(this)" data-type="index">首页</a>
    				<a href="#task" onclick="show(this)" data-type="task">任务</a>
    			</div>
    			<div id="content" style="background-color: aquamarine;position: absolute;top: 20%;right: 0;bottom: 0;left: 0;">
    				<!-- <div id="index" style="background-color: aqua; 100%;height: 100%;">我是首页</div>
    				<div id="task" style="background-color: aqua; 100%;height: 100%;display: none;">我是内容</div> -->
    			</div>
    		</div>
    
    	</body>
    	<style>
    		*{
    			margin: 0;
    			padding: 0;
    		}
    		html,body{
    			height: 100%;
    		}
    	</style>
    	<script>
    		function show(obj){
    			var type = $(obj).data("type");
    			$.getJSON("content.json",function(result){
    				console.log(type);
    				console.log(result);
    				$("#content").text(result[type]);
    			});
    		}
            /*核心方法:浏览器前进或后退*/
            window.onhashchange = hashchange;
    		function hashchange(){
    			if(location.hash=="#index"){
    				$.getJSON("content.json",function(result){
    					$("#content").text(result["index"]);
    				});
    			}
    			if(location.hash=="#task"){
    				$.getJSON("content.json",function(result){
    					$("#content").text(result["task"]);
    				});
    			}
    			if(!location.hash){
    				$("#content").text("");
    			}
    		}
    	</script>
    </html>
    
    
    {
    	"index":"我是首页",
    	"task":"我是内容"
    }
    
原文地址:https://www.cnblogs.com/mwss/p/11131411.html