获取当前网页的URL是常见的前端操作,常用的方法有两种:document.URL和location.href。
获取当前网页的URL是常见的前端操作,常用的方法有两种:document.URL和location.href。
document.URL
document.URL
属性返回当前文档的URL。
它与 location.href
属性非常相似,但有一些细微的区别。 document.URL
是只读的,而 location.href
是可读可写的。
以下是一个返回具有document.URL
属性的完整示例:
<!doctype html>
<html>
<head>
<title>Document.URL Example</title>
</head>
<body>
<p>The current URL is: <script>document.write(document.URL)</script></p>
</body>
</html>
上述示例将在网页上显示当前URL。 这个URL会被写入一个段落标签中,使用JavaScript的 document.write() 方法直接写入该URL。
location.href
location.href
属性也返回当前文档的URL字符串。
但是,location.href
是一个可读写属性,这意味着您可以使用它来调整文档的URL。只需将新URL字符串分配给 location.href
即可。
以下是一个返回具有location.href
属性的完整示例:
<!doctype html>
<html>
<head>
<title>Location.Href Example</title>
</head>
<body>
<p>The current URL is: <script>document.write(location.href)</script></p>
<button onclick="location.href='https://www.google.com'">Go to Google</button>
</body>
</html>
上述示例中,一个按钮被添加,当按钮被单击时,将调用 location.href
将URL修改为https://www.google.com。
您可以使用两种方法之一来获取当前文档的URL。document.URL
方法是只读的,用于读取文档的URL。location.href
是可读写的,可以用于读取或写入文档的URL。
本文标题为:获取当前网页document.url location.href区别总结


基础教程推荐
- ajax验证用户名和密码的实例代码 2022-12-28
- 使用postcss-plugin-px2rem和postcss-pxtorem(postcss-px2rem)-px自动转换rem的配置方法-vue-cli3.0 2023-10-08
- javascript实现获取浏览器版本、浏览器类型 2023-12-20
- Web前端之vuex基础 2023-10-08
- 7.表格标签.html 2023-10-27
- Unicode中的CJK(中日韩统一表意文字)字符小结 2022-09-21
- CSS将div内容垂直居中案例总结 2022-11-23
- wepy微信小程序框架加入版本更新提示 2022-10-30
- 不依赖Flash和任何JS库实现文本复制与剪切附源码下载 2023-12-01
- 编写轻量ajax组件第三篇实现 2022-12-18