Location href 属性

JavaScript Location  对象

href属性设置或返回当前页面的完整URL。

语法:

返回href属性:

location.href

设置href属性:

location.href = URL
var x = location.href;
document.querySelector("#output").innerHTML = x;
测试看看‹/›

浏览器兼容性

所有浏览器都完全支持href属性:

属性
href

属性值

描述
URL字符串,指定链接的URL。
可能的值:
  • 绝对URL-绝对路径是从文件系统根目录开始的路径。它始终包含文件的完整URL(例如href="https://www.nhooo.com/html/")

  • 相对网址 -指向网站中的文件(例如href="/ html /")

  • 锚点URL-指向页面内的锚点(例如location.href ="#empty_element")

  • 新协议 -指定其他协议(例如
    location.href="ftp://myftpserver.com",
    location.href="mailto:someone@example.com"
    或location.href="file:// host / path /example.txt")

技术细节

返回值:一个字符串,表示页面的整个URL,包括协议(例如https://)

更多示例

将href值设置为指向另一个网站:

location.href = "https://www.nhooo.com";
测试看看‹/›

将href值设置为指向页面内的锚点:

location.href = "#top";
测试看看‹/›

此示例显示所有位置属性:

var txt = "";
txt += "<p>Host: " + location.host + "</p>";
txt += "<p>Hostname: " + location.hostname + "</p>";
txt += "<p>Href: " + location.href + "</p>";
txt += "<p>Origin: " + location.origin + "</p>";
txt += "<p>Pathname: " + location.pathname + "</p>";
txt += "<p>Protocol: " + location.protocol + "</p>";
txt += "<p>Search: " + location.search + "</p>";
document.write(txt);
测试看看‹/›

相关参考

位置参考:location.host属性

位置参考:location.hostname属性

位置参考:location.pathname属性

位置参考:location.protocol属性

JavaScript Location  对象