首页 > 解决方案 > jquery ajax() 后退按钮不会改变内容

问题描述

我用本地文件的 hashchange 制作了简单的 $.ajax(),但是后退按钮只更改 url,而不是内容。我发现没有什么似乎对我有用。有人可以帮我吗?

  $(document).on('click', ".nextPage2", () => {
    $.ajax({
      url: 'page2.html',
      dataType: "html",
      success: function(result) {
        $('.content').html(result);
      }
    });
    window.location.hash = 'looks';
    return false;



  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="content"></div>



    <button type="button" class="nextPage2" name="button">page2</button>

标签: jquery

解决方案


当您更改 URL 时,您也在使用 JavaScript 来修改 DOM。

您需要监听URL 的更改并使用 JavaScript再次修改 DOM 。

function navigated() {
    if (location.hash === '#something-different') {
        $('.content').html("The content for something-different");
    }
}

window.addEventListener("hashchange", navigated);

推荐阅读