Home > Web Front-end > JS Tutorial > How to use the A tag to get the absolute path of the current directory in Javascript_javascript tips

How to use the A tag to get the absolute path of the current directory in Javascript_javascript tips

WBOY
Release: 2016-05-16 16:11:44
Original
1789 people have browsed it

When it comes to path-related issues, everyone will think of window.location. Indeed, this object provides quite a lot of path information, among which the commonly used ones include:

1.location.href: The complete URL of the current page
2.location.pathname: The path name in the current URL
3.location.hash: Anchor point
in the current URL 4.location.search: query parameters in the current URL

However, location does not have an attribute that can directly obtain the absolute path of the current directory (excluding the file name). Through Google, I found some wrong methods, such as separating the URL into an array through "/", removing the last item of the array and then concatenating it into a string. But if the file name is not specified in the URL, the result is completely wrong.

Based on past coding experience, the href attribute of the a element will always return an absolute path, which means it has the ability to convert relative paths into absolute paths. I tried it using the following code, and it worked:

Copy code The code is as follows:

var a = document.createElement('a');
a.href = './';
alert(a.href);
a = null;

Unfortunately, this method is not valid under the old IE 6/7. When alert(a.href) is executed, "./" still pops up. Later, I found that someone had also asked this question on Stackoverflow, and the solution was very simple. Just inject a through innerHTML:
Copy code The code is as follows:

var div = document.createElement('div');
div.innerHTML = '";
alert(div.firstChild.href);
div = null;

Someone may ask: Why not use regular expressions? My answer is: You need to consider whether there is a file name, whether there is an anchor point, and whether there are query parameters. This regular expression may be quite complicated.
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template