JavaScript location 对象中包含了有关当前页面链接(URL)的信息,例如当前页面的完整 URL、端口号等,我们可以通过 window 对象中的 location 属性来获取 location 对象。由于 window 对象是一个全局对象,因此在使用
window.location
时可以省略 window 前缀,例如
window.location.href
可以简写为
location.href
。
location 对象中的属性
下表中列举了 JavaScript location 对象中常用的属性及其描述:
</head>
<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 对象中常用的方法及其描述:
</head>
<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>
关注公众号「
站长严长生
」,在手机上阅读所有教程,随时随地都能学习。本公众号由
C语言中文网站长
亲自运营,长期更新,坚持原创。
微信扫码关注公众号