我正在使用 Ajax 在 div 中打开部分页面。但是当我刷新或点击后退按钮时,它只是没有做它应该做的事情。 我阅读并尝试了很多方法来使其发挥作用,但它就是不想发挥作用。 我现在的情况是,当我点击刷新或后退按钮时,我的地址栏会给出正确的页面,但我的 div 不会发生变化(例如,地址栏显示:/projects.php,但页面/div 仍在 index.php 上) )
我只想使用后退/前进按钮,当我刷新页面时,它必须保持在同一页面并且不要返回到第一个主页。
这是我的代码,希望有人能提供解决方案:
Html - 我的菜单
<div id="buttons">
<a class="menu" id="page1" href="#Home">Home</a><span>|</span>
<a class="menu" id="page2" href="#Projects">Projects</a><span>|</span>
<a class="menu" id="page3" href="#About">About</a><span>|</span>
<a class="menu" href="#Contact">Contact</a>
</div>
.加载部分
$(document).ready(function() {
$("#page1").click(function(){
$('#content').load('index.php #content');
});
$("#page2").click(function(){
$('#content').load('projecten.php #content');
});
$("#page3").click(function(){
$('#content').load('overons.php #content');
});
});
.haschange 部分
$(function(){
// These two properties, set after jQuery and the hashchange event plugin are
// loaded, only need to be used when document.domain is set (to fix the "access
// denied" error in IE6/7).
$.fn.hashchange.src = '../../document-domain.html'; //--- I still dont know what to do with this, but i guess its only for IE6/7 ---//
$.fn.hashchange.domain = document.domain;
// Bind an event to window.onhashchange that, when the hash changes, gets the
// hash and adds the class "selected" to any matching nav link.
$(window).hashchange( function(){
var hash = location.hash;
// Set the page title based on the hash.
document.title = 'The hash is ' + ( hash.replace( /^#/, '' ) || 'blank' ) + '.';
// Iterate over all nav links, setting the "selected" class as-appropriate.
$('#buttons a').each(function(){
var that = $(this);
that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
});
})
// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
$(window).hashchange();
});
最佳答案
当您仅更改片段时,页面不会重新加载或执行任何操作。
这就是 SPA(单页应用程序)的问题 - 它们不会重新加载页面。这就是为什么例如即使 #
(又名片段)后面的 URL 发生变化,Gmail 也会保持页面状态。打开不同的文件夹和/或电子邮件,然后查看 URL 片段是否发生变化。
您需要监听这些事件并执行类似于您自己的 $('#pageN').click()
处理程序的操作。如果用户打开 http://yourserver/#page2 也可以执行类似的操作直接地。如果这适用于您,请考虑 SEO。
查看类似问题:javascript - Detecting Back Button/Hash Change in URL - Stack Overflow (请尝试使用 HTML5 API if you can ),
参见例如Intelligent State Handling · browserstate/history.js Wiki了解一些背景信息。
或者创建完全独立的页面,其中 URL 路径(在 #
更改之前)。就像过去的美好时光一样。
关于javascript - Ajax .load 刷新/后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39245873/