在 js 方面我几乎是个新手,所以如果我错过了一些非常简单的东西,我很抱歉。
基本上,我已经对使用history.pustate和popstate进行了一些研究,并且我已经将查询字符串添加到url的末尾(
?v=images
)或(?v=profile
)...( v
意思是“查看”)通过使用这个:
var url = "?v=profile"
var stateObj = { path: url };
history.pushState(stateObj, "page 2", url);
我想这样做,这样我就可以将内容加载到 div 中,但无需重新加载我使用
.load()
函数完成的页面。
然后我使用了这段代码:
$(window).bind('popstate', function(event) {
var state = event.originalEvent.state;
在
$(document).ready()
部分,后来在 <script>
标签内尝试过,但都不起作用。
我不知道如何制作它,因此当我使用后退按钮时内容会发生变化,或者至少制作它以便我可以触发我自己的函数来执行此操作;我假设它与状态对象有关?!我似乎在网上找不到任何可以清楚解释该过程的内容。
如果有人可以帮助我,那就太棒了,提前感谢任何帮助我的人!
只有当有一个状态时,
popstate
才包含一个状态。
当事情像这样时:
pushState
然后就没有状态了,因为初始页面是定期加载的,而不是
pushState
。结果, onpopstate
事件被触发,且 state
为 null
。所以当它是null
时,就意味着应该加载原始页面。
您可以实现它,以便一致地调用
history.pushState
,并且您只需要提供如下状态更改函数:单击此处获取 jsFiddle 链接
function change(state) {
if(state === null) { // initial page
$("div").text("Original");
} else { // page added with pushState
$("div").text(state.url);
}
}
$(window).on("popstate", function(e) {
change(e.originalEvent.state);
});
$("a").click(function(e) {
e.preventDefault();
history.pushState({ url: "/page2" }, "/page2", "page 2");
});
(function(original) { // overwrite history.pushState so that it also calls
// the change function when called
history.pushState = function(state) {
change(state);
return original.apply(this, arguments);
};
})(history.pushState);
也许这不是最好的解决方案,也许它不适合您的需求。但对我来说,最好重新加载页面。因此页面是一致的,它根据当前查询字符串加载所有内容。
$(document).ready(function() {
$(window).on("popstate", function (e) {
location.reload();
});
});
只需添加现有答案的普通 JS 等效项,您可以这样做:
window.addEventListener("popstate", function (e) {
window.location.reload();
});
进一步阅读: