获取当前网页的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区别总结
基础教程推荐
- vue离线环境如何安装脚手架vue-cli 2025-01-19
- 基于Vue制作组织架构树组件 2024-04-08
- 关于文字内容过长,导致文本内容超出html 标签宽度的解决方法之自动换行 2023-10-28
- js禁止页面刷新与后退的方法 2024-01-08
- 浅析canvas元素的html尺寸和css尺寸对元素视觉的影响 2024-04-26
- 浅谈Vue2和Vue3的数据响应 2023-10-08
- Ajax实现动态加载数据 2023-02-01
- JS前端广告拦截实现原理解析 2024-04-22
- CSS3的几个标签速记(推荐) 2024-04-07
- this[] 指的是什么内容 讨论 2023-11-30
