URL API和Location
URL
创建URL
使用URL对象时,要传入一个绝对URL作为参数
let url = new URL("https://127.0.0.1:8080/path/name?age=18&sex=man#hashtest") url.href // https://127.0.0.1:8080/path/name?age=18&sex=man#hashtest url.origin // https://127.0.0.1:8080 url.protocol // https: url.host // 127.0.0.1:8080 url.hostname // 127.0.0.1 url.port // 8080 url.pathname // /path/name url.search // ?age=18&sex=man url.hash // #hashtest
组合url
我们也可以通过URL对象来组合一个新的url
let newUrl = new URL("http://127.0.0.1") newUrl.port = "5000" newUrl.pathname = "/path/name" newUrl.search = "age=88" newUrl.toString() // http://127.0.0.1:5000/path/name?age=88
查询修改query参数
通过searchParams可以对query参数进行查询修改等操作
let searchUrl = new URL("https://example.com/search") // 添加参数,若参数已存在,依然会添加 searchUrl.searchParams.append("name", "liuxiang") searchUrl.search // ?name=testname // 修改参数若含有同名参数,则全部合并成一个修改后的值,最后只剩一个相应的键值对 searchUrl.searchParams.set("name", "yaoming") searchUrl.search // ?name=yaoming // 查询参数的值 searchUrl.searchParams.get("name") // yaoming // 查询参数是否存在 searchUrl.searchParams.has("name") // true searchUrl.searchParams.has("age") // false // 当有同名参数时,会查询第一个值 searchUrl.searchParams.get("name") // yaoming // 删除 searchUrl.searchParams.delete("name")
Location
window 和 document对象的location属性都引用的是location对象,该对象表示当前窗口显示文档的URL,也提供了在窗口中加载新文档的API
Location对象与URL对象非常相似,可以使用protocol、hostname、port、path访问当前文档URL的不同部分,而herf属性以字符串形式返回整个URL,就如同toString()一样,search属性返回URL中?开头的部分(query参数部分),若想解析,可以借助URL对象
let url = new URL(window.location) let query = url.searchParams.get("name")
document.URL也返回文档的URL,但是并非URL对象,而是一个string
document.URL // http://127.0.0.1:5500/javascript/10.html
document.location
window.location
修改当前文档
直接修改location
window.location = "https://www.baidu.com/"
修改相对URL,可使用/和..辅助修改
document.url // http://127.0.0.1:5500/javascript/10.html document.location = "index.html" // http://127.0.0.1:5500/javascript/index.html
修改path直接修改所有的路由项
// 相当于 document.location = "../test/index.html" // 主要是服务器地址后面的路径 // document.location.pathname = "test/index.html" // http://127.0.0.1:5500/test/index.html
修改参数
location.search = "?name=" + 2
方法
assign跳转至新文档的方法,可以后退回原来的文档
window.location.assign("https://www.baidu.com")
replace会擦除上一个文档的记录,使得其不能后退
window.location.replace("https://www.baidu.com")
reload重新加载当前文档
window.location.reload()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器