繁体   English   中英

如何在AJAX页面导航中使用锚的href

[英]How to use href of an anchor with AJAX page navigation

我遇到以下问题:我试图基于纯AJAX页面导航创建HTML5页面。 所以我在主页上有“ index.html”。 这个包含我的CSS,脚本和菜单。 菜单如下所示:

<ul>
    <li><a id="startLink" class="navlink" href="pages/start.html">Start</a></li>
    <li><a class="navlink" href="pages/test.html">Test</a></li>
</ul>

通过单击其中一个锚点,我调用JavaScript,通过AJAX调用将“ href”下的页面加载到“ index.html”上的div中。 因此,我的主页永远不会重新加载,所有新内容仅显示在容器中。 该函数如下所示:

$(document).ready(function()
{
var popped = ("state" in window.history && window.history.state !== null), initialURL = location.href;

$(".navlink").click(function(e)
{
    var link    = $(this);
    var href    = link.attr("href");

    loadContent(href);
    window.history.pushState(null, null, href);

    e.preventDefault();
});

$(window).bind("popstate", function(e)
{
    // Ignore inital popstate that some browsers fire on page load
    var initialPop = !popped && location.href == initialURL;
    popped = true;
    if (initialPop) return;

    loadContent(location.pathname);
});

init();
});

function init()
{
    $("#startLink").click();
};

function loadContent(url)
{
    $("main").load(url);
};

我正在使用history.pushState和popstate函数来处理浏览器历史记录并在浏览器中显示URL。 这很好,但是现在我们来解决我的问题。

当我加载index.html时,我的init()函数单击开始锚点以在页面上显示一些初始内容。 好吧,现在,如果我要转到test.html,浏览器将向我显示“ Host / Somepath / pages / pages / test.html”之类的路径。 与开始相同:... / pages / pages / start.html。 我想原因是锚点上的我的href,因为浏览器认为他已进入我的文件夹页面并显示start.html。 他想从那里导航到页面/页面/以转到我菜单中的任何其他页面。 我的项目结构看起来像这样:

  • index.html
  • 的CSS
  • 图片
  • 剧本
  • 页数
    • start.html
    • test.html

有谁知道我该如何处理这个问题? 我不想将所有html放在一个文件夹中,我需要子文件夹来对项目进行结构化。

尝试使用HTML5 localStoragesessionStorage

样例代码

window.sessionStorage.setItem('isFirst', true);
$(document).ready(function () {

  if(window.sessionStorage.getItem('isFirst')){
    window.sessionStorage.setItem('isFirst', false);
    //Put your code here. It will work only once
    init();
  }    
});

您可以阅读有关HTML本地和会话存储点击的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM