Home Web Front-end JS Tutorial Detailed explanation of how to use JS hash to create a single-page web application

Detailed explanation of how to use JS hash to create a single-page web application

May 05, 2018 pm 04:23 PM
hash javascript web

This article mainly introduces the detailed explanation of the method of using JS hash to create a single-page web application. It has a certain reference value. Now I share it with you. Friends in need can refer to it

Preface

This article mainly introduces to you the relevant content about using JS hash to create single-page web applications. It is shared for your reference and learning. I won’t say much more below, let’s come together. Let’s take a look at the detailed introduction.

1. What is hash

The hash we are going to talk about here (also called hash) refers to the hash of the location object in JS Property, which returns zero or more characters followed by # in the URL. Usually, we can get the hash value or set the hash value through location.hash. Of course, we can also set the hash value by setting the href attribute of the a tag. When the user clicks the a tag, the hash value of the page can be changed.

For example:

/** JS方式 **/
location.hash = 'hash'; //设置hash,该代码执行后URL后面增加“#hash”字符串
console.log(location.hash); //获取hash
Copy after login

/** HTML方式 **/
<a href="#hash" rel="external nofollow" >点击改变hash</a> <!-- 点击后URL后面增加“#hash”字符串 -->
Copy after login

It is worth noting that , no matter how the hash value is changed, the page will not refresh.

2. What is the use of hash

1. Set anchor link

By setting anchor Links (that is, the above-mentioned HTML method) can make the page slide to the specified position according to the element ID after clicking the link, even after the page jumps.

2. Implement the production of single-page applications

The corresponding elements can be displayed or hidden according to changes in hash values, thereby achieving single-page switching without page refresh. .

3. What is a single page web application?

A single page web application (SPA) is a single page web application. A page application is a web application that loads a single HTML page and dynamically updates that page as the user interacts with the application.

The above is Baidu Encyclopedia's explanation of Single Page Application (SPA), and using hash can very conveniently achieve switching between "pages".

4. How to use hash to create a SPA

To put it simply, only the first page is displayed, and then the hash value is changed. Switch to display different pages and hide the previous page.
Write a simple Demo here:

1. First write the HTML structure

<article class="container">
 <section id="page1" class="page cur">第一页</section>
 <section id="page2" class="page">第二页</section>
 <section id="page3" class="page">第三页</section>
</article>
<nav id="nav" class="bottom-nav">
 <ul>
  <li>第一页</li>
  <li>第二页</li>
  <li>第三页</li>
 </ul>
</nav>
Copy after login

2. Then set the CSS style for it

.page{ display: none; /* 其他样式省略 */}
.page.cur{ display: block;}
/* 其他样式省略 */
Copy after login

##3. Write Javascript to achieve single page switching

window.onload = function () {
 var nav = document.getElementById(&#39;nav&#39;);
 var navLi = nav.getElementsByTagName(&#39;li&#39;);
 for(var i = 0,len = navLi.length; i < len; i++){
  (function (i) { 
   navLi[i].onclick = function () { //点击nav中的li,改变hash值
    location.hash = &#39;page&#39; + (i+1);
   }
  })(i);
 }
 location.hash = &#39;page1&#39;; //每次页面重新加载时都回到page1
 window.onhashchange = function (e) { 
  //当hash变化时,执行hashchange事件,该事件具有oldURL和newURL两个事件属性,分别代表前一个URL和目前的URL
  var oldHash = e.oldURL.split(&#39;#&#39;)[1]; //取得前一个hash
  var newHash = e.newURL.split(&#39;#&#39;)[1]; //取得当前hash
  var oldPage = document.getElementById(oldHash);
  var newPage = document.getElementById(newHash);
  oldPage.classList.remove(&#39;cur&#39;); //隐藏前一个page
  newPage.classList.add(&#39;cur&#39;);  //显示当前page
 };
}
Copy after login

There are a few things to note here. IE is not compatible with the two attributes oldURL and newURL, so this method has certain limitations. Of course, a better way is to initially store the hash value in a variable as oldHash. The specific method is as follows:

/**** 前面代码省略 ****/
location.hash = &#39;page1&#39;;
var oldHash = location.hash;
window.onhashchange = function (e) {
 var newHash = location.hash;
 var oldPage = document.querySelector(oldHash);
 var newPage = document.querySelector(newHash);
 oldPage.classList.remove(&#39;cur&#39;);
 newPage.classList.add(&#39;cur&#39;);
 oldHash = newHash;
};
Copy after login

There is another thing to note here. , that is, classList is not compatible with IE9 and below browsers. It is best to achieve the same effect by processing the className attribute, which will not be detailed here.

The above is the detailed content of Detailed explanation of how to use JS hash to create a single-page web application. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages ​​to enable data exchange and information sharing between different computers.

See all articles