javascript - 使用 AJAX 更改 div 内容 - 如何将导航显示为散列/ anchor

标签 javascript jquery html ajax

我想创建一个页面来刷新 div 异步中的内容,同时为用户提供一个 anchor 以允许直接访问 div 中的内容。 (例如 www.website.co.uk/#page1)

我已经设法让内容可以更新 1 页,但是,如果我添加多个页面,它就会停止工作

另外 - 如果我要导航到 URL website.co.uk/#page1,它不会显示 #page1。

有人能帮忙吗?

这是我当前的代码:

HTML :

<h5> <a href="#page1">Test</a></h5>
<h5> <a href="#page2">Test2</a></h5>

JS :

<script type="text/javascript">
    var routes = {
        '#page1' : '{{site.url}}/page1'
        '#page2' : '{{site.url}}/page2'
    };
    var routeHandler = function( event ) {
        var hash = window.location.hash, 
            xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("div1").innerHTML = xhttp.responseText;
            }
        };
        xhttp.open("GET", routes[hash], true);
        xhttp.send();    
    };
    window.addEventListener('hashchange', routeHandler);
    window.addEventListener('load', function() {
        var hash = window.location.hash;
        if (routes.hasOwnProperty(hash)) routehandler();
    });
</script>

最佳答案

你犯了一些小的 js 错误。 所以这是你的固定代码

html:

<h5> <a href="#page1">Test</a></h5>
<h5> <a href="#page2">Test2</a></h5>
<div id="div1"></div>

javascript:

  //change these routs
  var routes = {
    '#page1': '/page1.html',
    '#page2': '/page2.html'
  };

  var routeHandler = function() {

    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        document.getElementById("div1").innerHTML = xhttp.responseText;
      }
    };

    xhttp.open("GET", routes[window.location.hash], true);
    xhttp.send();

  };

  window.addEventListener('hashchange', routeHandler);
  window.addEventListener('load', function() {
    var hash = window.location.hash;
    if (routes.hasOwnProperty(window.location.hash)) routeHandler();
  });

关于javascript - 使用 AJAX 更改 div 内容 - 如何将导航显示为散列/ anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38146326/

相关文章:

javascript - 使用 html2canvas 创建网页截图(无法正确初始化)

javascript - 重用 JavaScript 函数

javascript - 向 Javascript/Jquery 添加多个属性

javascript - 如何将事件附加到 iframe 中的按钮

javascript - 想在只有一页的时候动态隐藏信息

javascript - 如何使用正则表达式删除 javascript 中字符串开头和结尾的 <br> ?

javascript - 将 Map 复制到现有 Map 的最高效方法

html - 对当前节点索引使用 Xpath Count()

javascript - 外部 JS 文件 + jquery + css

javascript - JQuery 绑定(bind) + bootstrap 不起作用