我試圖按照此處使用的示例:http://html5.gingerhost.com/ 而不是使用JSON的,我決定使用jQuery的.load()來代替,pushState的刷新頁面
這裏是我的代碼:
$(function() {
$('a').click(function(e) {
$('img#logo').stop().hide().fadeIn("slow");
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$('#load').load(url + " #load2").stop().hide().fadeIn('slow');
}
的例如的loadContent功能:
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
HTML:
<head>
<meta charset="utf-8">
<title>Andy Simon</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="javascript.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Raleway:100' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="main">
<div id="top">
<div id="logo">
<div>
<a id="logo" href="index.html"><img id="logo" src="logo1.png" /></a><span id="logo_text">simon</span>
</div>
</div>
<div id="nav">
<a class="nav_link" id="work" href="work.html"> work . </a>
<a class="nav_link" id="work" href="work.html"> about . </a>
<a class="nav_link" id="work" href="contact.html"> contact </a>
</div>
</div>
<div id ="middle">
<div id="load">
<div id="load2">
home home andy pandy home home home
</div>
</div>
</div>
<div id="foot">
</div>
</div>
</body>
當我點擊一個鏈接,頁面重新加載,而這正是我想避免的。我認爲我的e.preventDefault()會停止。任何幫助表示讚賞!
可能會發生一些錯誤,並且'preventDefault'不會因爲它而執行。嘗試使用類似螢火蟲控制檯的「不乾淨」(或類似)選項打開。它會告訴你在你的頁面上做的JS錯誤 – Timur