[英]Change page and change URL without refresh and keep content after refresh , like ReactJS website
我尝试使用 jQuery 的 load() function 来更改/加载内容而无需重新加载。 这行得通,但问题是:URL 保持不变!
即使我使用 history.pushState() 更改 URL,也不能解决问题。 例子:
用著名的window.history.pushState("object or string", "Title", "/new-url");
Important: index.html, about.html and contact.html are existing files that will load with the jquery function below.
HTML:
<div class="navbar">
<div class="content">
<div class="logo">My logo</div>
<ul class="pages">
<li id="index">Index</li>
<li id="about">About us</li>
<li id="contact">Contact</li>
</ul>
</div>
</div>
<section id="page">
<div class="content">
<!-- PAGES LOAD HERE -->
</div>
</section>
<div class="footer">
<div class="content">
--Footer-- All rights reserved.
</div>
</div>
JS:
$(document).ready(function () {
$('li').on("click", function () {
$pageName = $(this).attr('id');
$('#page .content').load(`pages/${$pageName}.html`);
$('li').removeClass('active'); //only to remove the selection of actual page in CSS
$(this).addClass('active'); //only to add the selection of actual page in CSS
window.history.pushState("object or string", "Title", `pages/${$pageName}.html`);
})
})
您正在描述“路由”,这是与正在显示的内容匹配的 URL 的概念。
在 jquery 中,我建议使用谷歌搜索:jquery 路由器或javascript router
如果您正在编写其他语言,则可以 google [language] router
。
最近谷歌正在提出https://www.npmjs.com/package/jqueryrouter现在正在转发到https://github.com/scssyworks/silkrouter
选择路由器后,请阅读文档并提出更多问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.