【发布时间】:2018-09-17 02:31:02
【问题描述】:
如果我当前位于 URL"example.com/somepage#somehash" 并调用 window.location.hash = "anotherhash",则 URL 将更改为 "example.com/somepage#anotherhash"。这会触发 window.hashashchange 事件。
如果我当前位于 URL "example.com/somepage?a=1&b=two" 并调用 window.location.replace("?one=1&two=2"),则 URL 将更改为 "example.com/somepage?one=1&two=2"。
我已经阅读了MDN docs,但我找不到它会触发的内容。
- 有吗?
- 如果没有,有没有简单的方法来捕获该事件?
注意:
说我想确保不会触发页面重新加载是我的错。我想使用新 URL 根据查询字符串更新页面,例如使用 AJAX 请求。 window.history.pushState 是另一种选择,但据我所知,它也不会触发事件。
编辑
我看了@Taki 的回答。我创建了一个repl.it,因为当您转到全页视图时,您可以看到 URL 的变化。然而,即使使用preventDefault,页面仍在重新加载,这可以通过卸载事件回调中发布到页面的信息消失的事实来证明。因此,这不能用于客户端路由,这是我的目标。
index.html
<button id="myBtn">Click me</button>
<div id="info"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="index.js"></script>
index.js
console.log("index.js");
$('#myBtn').on('click', function(e)
{
console.log("button clicked")
window.location.replace("?one=1&two=2")
console.log(window.location.href);
});
$(window).on("beforeunload", function (event)
{
event.preventDefault(); // just to pause and see the cosdole
console.log("beforeunload");
console.log(event);
$('#info').append("<p>beforeunload</p>");
console.log(window.location.href); // capture the url
});
【问题讨论】:
标签: javascript html dom-events hashchange