我试图创建一个网页,当导航链接被点击时取代主div的内容。我已经能够实现pushstate函数来替换div内容并非常容易地更改url地址。当使用popstate函数单击后退/前进按钮时,我也能够获得内容刷新。然而,现在我点击第一个链接,它工作得很好,我点击下一个链接,它似乎应用2推送状态,第三次点击,应用3推送状态,等等。似乎有一个推循环发生在某个地方,但不确定它在哪里。我正在寻找一些关于如何消除多个推送状态的建议,以便它们不会在我的历史中重复。
HTML代码:<nav id="headerNav">
<ul>
<li><button class="navButton" id="signIn" href="./content/signIn.php" name="reply" title="SignIn">Sign In</button></li>
<li><button class="navButton" id="signUp" href="./content/registration.php" name="registration" title="Registration">Sign Up</button></li>
<li><button class="navButton" id="about" href="./content/about.php" name="settings" title="About">About</button></li>
</ul>
</nav>
<section id="mainContent">
<!-- CONTENT PAGES REPLACE HERE -->
<?php
include ('./content/start.php');
?>
</section>
Javascript $(document).ready(function() {
if (window.history && history.pushState) {
$(".navButton").click(function(e) {
e.preventDefault();
$("#mainContent").fadeOut().load($(this).attr("href")).fadeIn();
history.pushState(null, $(this).attr("title"), $(this).attr("name"));
});
}
});
window.addEventListener('popstate', function() {
//WHEN BACK/FORWARD CLICKED CHECKS URL PATHNAME TO DETERMINE WHICH CONTENT TO PLACE IN DIV
if (location.pathname == "/index.php") {
$("#mainContent").load("./content/start.php");
} else {
$("#mainContent").load("./content" + location.pathname + ".php");
}
});
解决!这是我测试历史API的"if"条件。当我删除它时,它消除了重复的历史推送。我还让我的htaccess文件将所有键入的url重定向到允许对内容进行路径名比较的索引页。作品伟大,但我知道我将不得不解决书签如果以后的网站增长。现在,它按我需要的方式运行,这样我就可以继续前进了!
window.onload = function() {
// PUSHES CORRECT CONTENT DEPENDING ON URL PATH - ENSURES BACK/FORWARD AND BOOKMARKS WORK
if (location.pathname == "/index2.php") {
$("#mainContent").load("./content/start.php");
} else {
$("#mainContent").load("./content" + location.pathname + ".php");
}
// EVEN HANDLER TO DETECT CLICK OF NAVBUTTON CLASS
$(".navButton").click(function(e) {
$(this).addClass("active");
$(".navButton").not(this).removeClass("active");
var $mainContent = $("#mainContent");
var $href = $(this).attr("href");
var $title = $(this).attr("title");
var $name = $(this).attr("name");
// REPLACES CONTENT WITH DYNAMIC TRANSITION
$mainContent.fadeOut(100, function() {
$mainContent.load($href, function() {
$mainContent.fadeIn(100);
});
});
//CHANGES DOCUMENT TITLE SINCE PUSHSTATE CAN'T DO THIS YET
document.title = $title;
// PUSHES URL CHANGE AND HISTORY STATE TO BROWSER
history.pushState('', $title, $name);
//PREVENTS DEFAULT ACTION OF NAVBUTTON
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
if (location.pathname == "/index2.php") {
$("#mainContent").load("./content/start.php");
} else {
$("#mainContent").load("./content" + location.pathname + ".php");
}
};
};