问题描述
我试图理解 JavaScript 中的 popstate
事件,为此我创建了这个基于 AJAX 的简单导航网站。
这是home.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<header>
<a href="index.html">Home</a>
<a href="about.html">About</a>
</header>
<div id="main">
<h1>Home Page</h1>
<p>Lorem,ipsum dolor sit amet consectetur adipisicing elit. Repellendus eligendi suscipit aliquid. Mollitia ratione impedit ab,dicta reprehenderit veniam nam facere ipsam vel minus doloribus officia,odit dolorum alias error.</p>
</div>
<script src="nav.js"></script>
</body>
</html>
这是about.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<title>About Us</title>
</head>
<body>
<header>
<a href="index.html">Home</a>
<a href="about.html">About</a>
</header>
<div id="main">
<h1>About</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto placeat ipsam nam nobis exercitationem voluptatibus,officia impedit. Dolore,esse dignissimos enim porro aspernatur sit aperiam asperiores,maiores,hic velit quod.</p>
</div>
<script src="nav.js"></script>
</body>
</html>
这是脚本 nav.js
:
// implementing ajax-based navigation
var main = document.getElementById('main');
function makeRequest(url,callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'document';
xhr.open('GET',url);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this);
}
}
xhr.send();
}
window.onclick = function(e) {
if (e.target.href != window.location.href) {
history.pushState(null,'',e.target.href);
}
makeRequest(e.target.href,function(xhr) {
document.title = xhr.responseXML.title;
main.innerHTML = xhr.responseXML.getElementById('main').innerHTML;
});
e.preventDefault();
window.onpopstate = function(e) {
console.log('The popstate event has fired')
makeRequest(window.location.href,function(xhr) {
main.innerHTML = xhr.responseXML.getElementById('main').innerHTML;
});
}
}
我面临的问题详细如下:
-
在此页面上,我单击指向
about.html
的链接。结果,window.onclick
处理程序被触发,并最终使用 AJAX 动态显示文档about.html
。浏览器的标题以及 URL(由于history.pushState()
而发生的)也会发生变化。 -
现在我返回(使用浏览器的后退按钮),URL 更改为
index.html
,因此popstate
事件在window
上触发。在这里,我将index.html
的内容重新加载到当前文档中,一切正常。 -
我返回,这会将我带到 Google Chrome 的主页(每个新标签页的开头)。
-
现在,我继续前进。这会将我带到文档
index.html
。浏览器上显示的是index.html
的内容。到目前为止,一切正常。 -
我又往前走了。浏览器的 URL 也会更改为
about.html
及其标题。但是,这一次,popstate
事件不会触发。 URL 已更改为之前使用history.pushState()
设置的位置,因此我希望触发popstate
事件。然而,它没有。
在最后一步未触发 popstate
事件的原因是什么?
解决方法
您的 window.onpopstate = function(e) {
块应该在 window.onclick = function(e) {
块之外。