我使用 JQuery/Ajax 在名为 #container 的 div 中加载网站上的内容。我必须有不同类型的链接:
- 正常锚链接
- JQuery-触发器,当单击特定 div 时触发事件。
现在我想添加功能来支持后退和前进浏览器按钮以及书签功能。我遇到了history.js,但我遇到了一些问题,并且找不到如何正确使用它的真正简单的教程。
我的链接:
<a href='#imprint' class='link_imprint'>Imprint</a>
我读到 SEO 使用效果更好<a href="imprint/"
...但在我的服务器上找不到该 URL。所以我的first问题是,我如何确保 myurl.com/imprint 正常工作并且不会导致 404 页面?
来到history.js...目前我在index.php中包含了以下代码,就在<body>
<script>
$(document).ready(function(){
(function(window,undefined){
// Prepare
var History = window.History; // Note: We are using a capital H instead of a lower h
if ( !History.enabled ) {
// History.js is disabled for this browser.
// This is because we can optionally choose to support HTML4 browsers or not.
return false;
}
// Bind to StateChange Event
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
alert("state");
var State = History.getState(); // Note: We are using History.getState() instead of event.state
});
History.Adapter.bind(window,'anchorchange',function(){
});
var currentState = History.getState();
var currentUrl = currentState.url;
var urlParts = currentUrl.split('#');
$('#container').load('templates/'+ urlParts[1] +'.php');
$('#footer.credits').on('click','.link_imprint',function() {
var currentUrl = $(this).attr('href');
var urlParts = currentUrl.split('#');
History.pushState(null,null,currentUrl);
$('#container').load('templates/'+ urlParts[1] +'.php');
});
})(window);
});
使用此代码,单击链接后,URL 更改为:myurl/#imprint 并且 imprint.php 被加载到 container.php 中。但是,当我现在单击后退按钮时,URL 会发生变化,但内容仍然是印记中的内容。如何确保容器刷新旧内容?我想我忘记了什么,但我不知道我应该做什么。我尝试使用 statechange/anchorstate 但当我单击后退按钮时,这两个事件都不会被触发。
谢谢你的协助。
P.S:我向状态更改事件添加了警报,但它永远不会被触发。这不可能是正确的,对吧?当我点击链接并且 url 更改为 myurl.com/#imprint 时,我可以看到锚更改事件触发...