首页 > JavaScript
阅读:10796
JS Location对象:获取URL
JavaScript location 对象中包含了有关当前页面链接(URL)的信息,例如当前页面的完整 URL、端口号等,我们可以通过 window 对象中的 location 属性来获取 location 对象。由于 window 对象是一个全局对象,因此在使用
示例代码如下:
示例代码如下:
window.location 时可以省略 window 前缀,例如 window.location.href 可以简写为 location.href。location 对象中的属性
下表中列举了 JavaScript location 对象中常用的属性及其描述:| 属性 | 描述 |
|---|---|
| hash | 返回一个 URL 中锚的部分,例如:http://c.biancheng.net#js 中的 #js。 |
| host | 返回一个 URL 的主机名和端口号,例如 http://c.biancheng.net:8080。 |
| hostname | 返回一个 URL 的主机名,例如 http://c.biancheng.net。 |
| href | 返回一个完整的 URL,例如 http://c.biancheng.net/javascript/location-object.html。 |
| pathname |
返回一个 URL 中的路径部分,开头有个 /。 |
| port |
返回一个 URL 中的端口号,如果 URL 中不包含明确的端口号,则返回一个空字符串 ' '。 |
| protocol |
返回一个 URL 协议,即 URL 中冒号:及其之前的部分,例如 http: 和 https:。 |
| search |
返回一个 URL 中的查询部分,即 URL 中 ? 及其之后的一系列查询参数。 |
示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<a href="http://c.biancheng.net:8080/javascript/location-objcet.html?course=javascript&title=location#content" id="url"></a>
<script type="text/javascript">
var url = document.getElementById('url');
document.write("<b>hash:</b>" + url.hash + "<br>");
document.write("<b>host:</b>" + url.host + "<br>");
document.write("<b>hostname:</b>" + url.hostname + "<br>");
document.write("<b>href:</b>" + url.href + "<br>");
document.write("<b>pathname:</b>" + url.pathname + "<br>");
document.write("<b>port:</b>" + url.port + "<br>");
document.write("<b>protocol:</b>" + url.protocol + "<br>");
document.write("<b>search:</b>" + url.search + "<br>");
</script>
</body>
</html>
运行结果如下:
hash:#content
host:c.biancheng.net:8080
hostname:c.biancheng.net
href:http://c.biancheng.net:8080/javascript/location-objcet.html?course=javascript&title=location#content
pathname:/javascript/location-objcet.html
port:8080
protocol:http:
search:?course=javascript&title=location
location 对象中的方法
下表中列举了 JavaScript location 对象中常用的方法及其描述:| 方法 | 说明 |
|---|---|
| assign() | 加载指定的 URL,即载入指定的文档。 |
| reload() | 重新加载当前 URL。 |
| replace() | 用指定 URL 替换当前的文档,与 assign() 方法不同的是,使用 replace() 替换的新页面不会保存在浏览历史中,用户不能使用后退来返回该页面。 |
| toString() | 与 href 属性的效果相同,以字符串的形式返回当前完整的 URL。 |
示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<a href="http://c.biancheng.net:8080/javascript/location-objcet.html?course=javascript&title=location#content" id="url"></a>
<button onclick="myAssign()">assign()</button>
<button onclick="myReload()">reload()</button>
<button onclick="myReplace()">replace()</button>
<button onclick="myToString()">toString()</button>
<script type="text/javascript">
var url = 'http://c.biancheng.net';
function myAssign(){
location.assign(url);
}
function myReload(){
location.reload();
}
function myReplace(){
location.replace(url);
}
function myToString(){
var url = document.getElementById('url');
var str = url.toString();
alert(str);
}
</script>
</body>
</html>
ICP备案:
公安联网备案: