【发布时间】:2014-12-10 10:43:31
【问题描述】:
历史 API 中未执行初始 pushState。当我在浏览器上直接输入http://finoy.in/history/about时,并没有更新内容。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Simple History.js Ajax example by dansalmo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/history.js/1.7.1/bundled/html5/jquery.history.js"></script>
<style type='text/css'>
.hidden {
display: none;
visibility: hidden;
}
</style>
</head>
<body>
<a href="/history/home">Home</a>
<a href="/history/about">About</a>
<a href="/history/contact">Contact</a>
<a href="/history/other">Other</a>
<div id="content">
<div id="home">Home Page content</div>
</div>
<div id="hidden_content" class="hidden"></div>
<script type='text/javascript'>//<![CDATA[
$(function(){
var History = window.History;
if (History.enabled) {
State = History.getState();
console.log(window.location.pathname)
// set initial state to first page that was loaded
History.pushState({urlPath: document.location.href}, $("title").text(), State.data.urlPath);
} else {
return false;
}
var loadAjaxContent = function(target, urlBase, selector) {
var urlBase = '/history/demo.html';
$(target).load(urlBase + ' ' + selector);
};
var updateContent = function(State) {
//var selector = '#' + State.data.urlPath.substring(1);
var selector = '#' + State.data.urlPath.split('/').pop();
if ($(selector).length) { //content is already in #hidden_content
$('#content').children().appendTo('#hidden_content');
$(selector).appendTo('#content');
} else {
$('#content').children().clone().appendTo('#hidden_content');
loadAjaxContent('#content', State.url, selector);
}
};
// Content update and back/forward button handler
History.Adapter.bind(window, 'statechange', function() {
updateContent(History.getState());
});
// navigation link handler
$('body').on('click', 'a', function(e) {
var urlPath = $(this).attr('href');
var title = $(this).text();
History.pushState({urlPath: urlPath}, title, urlPath);
return false; // prevents default click action of <a ...>
});
});//]]>
</script>
</body>
</html>
我已经在根目录(历史文件夹)添加了一个 .htaccess 文件,其中包含:
# html5 pushstate (history) support:
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !index
RewriteRule (.*) index.html [L]
</ifModule>
【问题讨论】:
-
“当我接受
http://finoy.in/history/about”是什么意思? -
@Quentin "当我在浏览器上直接输入finoy.in/history/about"
标签: javascript html history.js html5-history