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()

 

posted @ 2021-12-15 22:50  邢韬  阅读(126)  评论(0编辑  收藏  举报