要返回到上一页,请按照以下步骤进行。
第1步:首先,制作一个HTML文件,将两个文件链接在一起。
第2步:作为第二步,创建链接页面1,并添加一个按钮和JS文件。
第3步:作为第三步,创建链接页面2,并添加一个按钮和JS文件。
第4步:让按钮发挥作用,以便按下它可以返回到前一页。
我们需要了解addEventListener()和window.history.back()来实现这个功能 addEventListener() 将一个事件处理程序附加到文档中
removeEventListener()
从文档中删除一个事件处理程序(已经用addEventListener()方法附加的)。
addEventListener()语法
document.querySelector('button').addEventListener('click',function)
addEventListener('click') 或 onmouseover, onmouseout, onfocus,onblur,click,dblclick
window.history.back():
history.back()方法加载历史列表中的前一个URL(页面)。
history.back()与点击浏览器的 "返回 "是一样的。
<button onclick="history.back()">Go Back</button>
语法
<button onclick="history.back()">Go Back</button>
<button onclick="history.forward()">Go Forward</button>
<button onclick="history.go(-2)">Go Back 2 Pages</button>
JavaScript代码
第1步:创建一个HTML文件并链接两个文件
返回到上一页.html
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Go back to previous page</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Home page </h1>
<a href="page1.html">Page 1</a>
<a href="page2.html">Page 2</a>
<p id="btn"></p>
</div>
<script>
let k= window.history.length
document.getElementById("btn").innerHTML=k
document.write("No.of tabs are finded by [ window.history.length ] method :" ,k)
</script>
</body>
</html>
第2步:创建链接的第1页,命名为page1.html,并在一个按钮上添加鼠标移动的功能
page1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Go back to previous page</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h2>Page 1</h2>
<button onmouseover="window.history.back()" > GoTo Prev Page</button>
<p id="btn"></p>
</div>
<!-- <script src="script.js">
document.getElementById("btn").innerHTML=window.history.length
</script> -->
</body>
</html>
第3步:创建名为page2.html的链接页面2,并添加一个按钮,添加JS文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Go back to previous page</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h2>Page 2</h2>
<button> GoTo Prev Page</button>
<p id="btn"></p>
</div>
<script src="script.js">
document.getElementById("btn").innerHTML=window.history.length
</script>
</body>
</html>
style.css
body{
text-align: center;
}
脚本.js
document.querySelector('button').addEventListener('dblclick', () =>{
window.history.back()
})