在JavaScript中,获取当前链接(即当前页面的URL)可以通过window.location
对象来实现。以下是一些常用的属性和方法:
window.location.href
:返回完整的URL字符串。window.location.protocol
:返回URL的协议部分(例如,http:
或https:
)。window.location.hostname
:返回URL的主机名部分(例如,www.example.com
)。window.location.port
:返回URL的端口号部分(例如,80
或443
)。window.location.pathname
:返回URL的路径名部分(例如,/path/to/page
)。window.location.search
:返回URL的查询字符串部分(例如,?query=param
)。window.location.hash
:返回URL的锚部分(例如,#section1
)。// 获取完整的URL
var fullUrl = window.location.href;
console.log("Full URL: " + fullUrl);
// 获取协议
var protocol = window.location.protocol;
console.log("Protocol: " + protocol);
// 获取主机名
var hostname = window.location.hostname;
console.log("Hostname: " + hostname);
// 获取端口号
var port = window.location.port;
console.log("Port: " + port);
// 获取路径名
var pathname = window.location.pathname;
console.log("Pathname: " + pathname);
// 获取查询字符串
var search = window.location.search;
console.log("Search: " + search);
// 获取锚
var hash = window.location.hash;
console.log("Hash: " + hash);
window.location.href
来实现页面跳转。window.location.href
来实现页面跳转。window.location.search
来获取URL中的查询参数。window.location.search
来获取URL中的查询参数。decodeURIComponent
来解码。decodeURIComponent
来解码。通过这些方法和属性,你可以灵活地获取和操作当前页面的URL,以满足各种前端开发需求。
领取专属 10元无门槛券
手把手带您无忧上云