获取当前网页的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区别总结


基础教程推荐
- webpack学习笔记一:安装webpack、webpack-dev-server、内存加载js和html文件、loader处理非js文件 2023-10-29
- 创建Vue3.0需要安装哪些脚手架 2025-01-16
- js判断一个对象是否在一个对象数组中(场景分析) 2022-10-21
- JSONObject与JSONArray使用方法解析 2024-02-07
- Loaders.css免费开源加载动画框架介绍 2025-01-23
- html5视频如何嵌入到网页(视频代码) 2025-01-22
- clientX,pageX,offsetX,x,layerX,screenX,offsetLeft区别分析 2024-01-08
- Django操作cookie的实现 2024-04-15
- 纯css实现漂亮又健壮的tooltip的方法 2024-01-23
- Bootstrap学习笔记之css组件(3) 2024-01-22