• 微信号
  • 微信号
目录

javascript

您当前的位置:首页 > 我的笔记 > javascript>JS Location对象:获取URL

JS Location对象:获取URL

location.href。

location 对象中的属性

下表中列举了 JavaScript location 对象中常用的属性及其描述:

? 及其之后的一系列查询参数。

示例代码如下:

<!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>