[英]URL-based single page app nav in pure JavaScript?
I'm trying to write a single-page web app in JavaScript. 我正在尝试使用JavaScript编写单页Web应用程序。 Desired behavior:
所需行为:
http://myapp.example.com
(the main page), or any other URL off of that domain for the first time, their browser downloads 1 large HTML file (and associated JS/CSS/image files, etc.). http://myapp.example.com
(主页)或该域之外的任何其他URL时,他们的浏览器会下载1个大型HTML文件(以及相关的JS / CSS /图像文件,等等。)。 --> so big upfront download <div>
elements that each represent a different "page"; <div>
元素,每个元素代表一个不同的“页面”。 only 1 "page" div will be displayed at any given time I'm wondering how to do this. 我想知道如何做到这一点。 I'd greatly prefer something jQuery-based rather than trying to write something homegrown.
我非常喜欢基于jQuery的内容,而不是尝试编写本地化的内容。 But if I have to write this code myself, then given the following general structure of the 1 HTML file:
但是,如果我必须自己编写此代码,则可以使用以下1 HTML文件的一般结构:
<html>
<head> ... </head>
<body>
<div id="home" class="page">
<!-- Content for home page, say http://myapp.example.com/#home. -->
</div>
<div id="about" class="page">
<!-- Content for About page, say http://myapp.example.com/#about. -->
</div>
<div id="contact" class="page">
<!-- Content for Contact page, say http://myapp.example.com/#contact. -->
</div>
<!-- Etc. for all other "pages" -->
</body>
</html>
How do I: 我如何:
You can use and set the window.location.hash
and use that value to $("#yourDivId").show()
and $("#yourDivId").hide()
your divs. 您可以使用并设置
window.location.hash
并将该值用于$("#yourDivId").show()
和$("#yourDivId").hide()
。
On the onload
you can $("#yourDivId").show()
the requested (or default if none was requested) div, and $("#yourDivId").hide()
the other divs. 在
onload
您可以$("#yourDivId").show()
所请求的div(如果没有请求, $("#yourDivId").hide()
默认值),而$("#yourDivId").hide()
是其他div。
And on each link, either directly change the hash and set the requested div visible. 并且在每个链接上,直接更改哈希值并将请求的div设置为可见。 Or set a timer that checks the hash on an interval to see if the hash has changed.
或设置一个计时器,以检查某个时间间隔上的哈希值以查看哈希值是否已更改。 (There is no native onhashchange event.)
(没有本地onhashchange事件。)
I think you should hide every div at start. 我认为您应该在开始时隐藏每个div。
$(div#page).hide();
Then, you can check the current URl by using: 然后,您可以使用以下方法检查当前的UR1:
var pathname = window.location.pathname;
Every time the user changes the URL: first hide every div, then check and show the desired div. 每次用户更改URL时:首先隐藏每个div,然后检查并显示所需的div。
That is the reason of Single Page Application Framework's existence. 这就是单页应用程序框架存在的原因。 I think it does worth learning some of the, such as AngularJS or BackboneJS.
我认为值得学习其中的一些,例如AngularJS或BackboneJS。
If you want to abuse the browser history, I suggest you read this article on history.pushState()
. 如果您想滥用浏览器历史记录,建议您阅读一下
history.pushState()
上的这篇文章 。 :-) :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.