search
HomeWeb Front-endJS Tutorialwindow.location.hash knowledge summary_basic knowledge

Location is a built-in object in JavaScript that manages the address bar. For example, location.href manages the URL of the page. Using location.href=url, you can directly redirect the page to the URL. Location.hash can be used to get or set the tag value of the page. For example, location.hash="#admin" of http://domain/#admin. A very meaningful thing can be done using this attribute value.

window.location.hash simple application

1. The meaning of #

# represents a position in the web page. The character to the right is the identifier of the position. For example,

 http://www.example.com/index.html#print

represents the print position of the web page index.html. After the browser reads this URL, it will automatically scroll the print position to the visible area.

Specify an identifier for the web page location. There are two methods. One is to use anchor points, such as , and the other is to use id attributes, such as

.

2. HTTP request does not include #

# is used to guide browser actions and is completely useless on the server side. Therefore, # is not included in the HTTP request.

For example, visit the following URL,

 http://www.example.com/index.html#print

The actual request sent by the browser is like this:

 GET /index.html HTTP/1.1

Host: www.example.com

As you can see, it is only requesting index.html, and there is no "#print" part at all.

3. Characters after #

Any characters that appear after the first # will be interpreted by the browser as a location identifier. This means that none of these characters will be sent to the server.

For example, the original intention of the following URL is to specify a color value:

 http://www.example.com/?color=#fff

However, the actual request made by the browser is:

 GET /?color= HTTP/1.1

Host: www.example.com

As you can see, "#fff" is omitted. Only when # is transcoded into # will the browser treat it as a literal character. In other words, the above URL should be written as:

 http://example.com/?color=#fff

4. Change # without triggering web page reload

Just change the part after #, the browser will only scroll to the corresponding position and will not reload the web page.

For example, from

 http://www.example.com/index.html#location1

changed to

 http://www.example.com/index.html#location2

The browser will not re-request index.html from the server.

5. Changing # will change the browser’s access history

Every time you change the # part, a record will be added to the browser's access history. Use the "Back" button to return to the previous position.

This is especially useful for ajax applications. Different # values ​​can be used to represent different access states, and then the user can be given a link to access a certain state.

It is worth noting that the above rules do not hold for IE 6 and IE 7, they will not increase the history due to the change of #.

6. window.location.hash reads # value

The property window.location.hash is readable and writable. When reading, it can be used to determine whether the status of the web page has changed; when writing, an access history record will be created without reloading the web page.

7. onhashchange event

This is a new event in HTML 5. When the # value changes, this event will be triggered. IE8, Firefox 3.6, Chrome 5, and Safari 4.0 support this event.

There are three ways to use it:

 window.onhashchange = func;

 

window.addEventListener("hashchange", func, false);

For browsers that do not support onhashchange, you can use setInterval to monitor changes in location.hash.

8. The mechanism of Google crawling #

By default, Google's web spiders ignore the # part of the URL.

However, Google also stipulates that if you want the content generated by Ajax to be read by the browsing engine, you can use "#!" in the URL, and Google will automatically convert the content following it into the value of the query string _escaped_fragment_ .

For example, Google found that the URL of the new version of twitter is as follows:

 http://twitter.com/#!/username

will automatically crawl another URL:

 http://twitter.com/?_escaped_fragment_=/username

Through this mechanism, Google can index dynamic Ajax content.

Let’s look at some netizens who encountered such a problem. As shown in the following code, every time you click a button on the page, the value in the browser address bar will be changed. In this way, you can deceive the browser (without sending any information to the browser). The server sends a new request), making its "back" and "forward" buttons available.

The current problem is that the browser values ​​​​have changed under ie6 and ff3, but only "forward" and "backward" can be used under ff3. Under ie, these two are gray and unavailable. Please tell me. Why?

The code is as follows

<html> 
<head> 
<script type="text/javascript"> 
//每次点击都会调用test(),它会改变url的值 
var i=0; 
function test(){   
  window.location.hash=i; 
  i++;   
} 
</script> 
</head> 
<body> 
<input type="submit" value="xxxxxxxxxxxxx" onclick="test()"/> 
</body> 
</html> 

The following is about the use of hash combined with ajax. Every time ajax retrieves data, the browser does not generate a history record after the page is updated. This means that the back and forward buttons lose their utility. In this case, hash and window can be combined. Use onhashchange. Note that ie6 and 7 do not support onhashchange, but you can use setInterval to check hash changes regularly, or check in onload.

Specific implementation:

<body>
  <div id="div1"></div>
  <input type="button" value="click" onclick="GetT()" /> 
</body>
</html>
<script type="text/javascript" src="js/AjaxHasPool.js">
</script>
<script type="text/javascript">
var ajax = new AjaxHasPool();
var method="get";
var url ="Handler.ashx";
var i = 1;
var obj = new Object();
function GetT()
{
  document.getElementById("div1").innerHTML=i; 
  ajax.Startup(null,url,method,ep);
}
function ep(xmlobj){
  eval("obj['"+i+"']="+i+";");
  location.hash="#"+i;
++i; 
}
window.onhashchange=function(){
var hashStr = location.hash.replace("#","");
if(typeof(eval("obj['"+hashStr+"']"))!="undefined") 
     document.getElementById("div1").innerHTML=eval("obj['"+hashStr+"']"); 
}
</script>

1.AjaxHasPool is its own encapsulated ajax class, in which ajax.Startup() is to send an ajax request;
2. The Object object saves historical records. If the object attribute is a number, it must be instantiated using obj["1"], otherwise it will violate the naming convention.
3. Use window.onhashchange to detect the hash value and obtain historical data.

Statement
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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor