在 jQuery 代码中高效地获取当前 URL 对许多 Web 开发任务至关重要,例如动态更新内容或实现自定义导航。本指南探讨了最有效的方法,阐明了它们的差异和最佳用例。
目录:
方法一:使用window.location.href
这是最直接和最广泛使用的方法。window.location.href
直接返回当前页面的完整 URL,包括协议、域名、路径和查询参数。
$(document).ready(function() {
let currentURL = window.location.href;
console.log(currentURL); // 输出完整的 URL
$("#myElement").text("当前 URL: " + currentURL);
});
方法二:使用document.URL
document.URL
提供与window.location.href
功能相同的结果,返回完整的 URL。虽然使用频率略低,但这仍然是一个完全有效的选项。
$(document).ready(function() {
let currentURL = document.URL;
console.log(currentURL); // 输出完整的 URL
$("#myElement").text("当前 URL: " + currentURL);
});
方法三:分解 URL
通常,您只需要 URL 的特定部分。window.location
对象提供属性来单独访问这些组件:
window.location.protocol
:(例如,“http:”,“https:”)window.location.hostname
:(例如,“www.example.com”)window.location.pathname
:(例如,“/path/to/page”)window.location.search
:(例如,“?param1=value1¶m2=value2”)window.location.hash
:(例如,“#anchor”)
let protocol = window.location.protocol;
let hostname = window.location.hostname;
// ... 根据需要访问其他属性 ...
console.log("协议:", protocol, "主机名:", hostname);
最佳实践和注意事项
虽然window.location.href
和document.URL
都很高效,但window.location.href
通常因其可读性和广泛使用而更受青睐。对于对 URL 组件的目标访问,请使用window.location
对象的各个属性。在处理特殊字符时,请务必使用encodeURIComponent()
和decodeURIComponent()
等函数正确处理 URL 编码和解码。