Web APIs中Location、URL和URLSearchParams接口

版权声明:本文为个人知识整理,欢迎指正、交流、转载。 https://blog.csdn.net/u014711094/article/details/83047450

1 Location Interface

The Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to.

  • Properties
let l = document.location

document.location === window.location	// true

// 等价
document.location = "https://www.csdn.net"
document.location.href = "https://www.csdn.net"

// 赋值后页面跳转
l.href			// http://localhost:8088/one.html?a=1&b=2#map
l.protocol		// http:
l.host			// localhost:8088
l.hostname		// localhost
l.port			// 8088
l.pathname		// /one.html
l.search		// ?a=1&b=2

l.hash			// #map, 仍在当前页面, 会跳到文档中相应位置
l.origin		// http://localhost:8088, 赋值无效

// mozilla开发文档中有此属性, 在chrome中测试不存在
l.username	// undefined
l.password	// undefined
  • Methods
let l = document.location

l.toString()		// l.href的同义词(synonym)

l.reload(true)		// 从服务器reload
l.reload()			// 从缓存或者服务器reload

l.assign("http://www.csdn.net")		// 添加到History
l.replace("http://www.csdn.net")	// 不添加到History

2 URL Interface

The URL interface represents an object providing static methods used for creating object URLs.
When using a user agent where no constructor has been implemented yet, it is possible to access such an object using the Window.URL properties (prefixed with Webkit-based browser as Window.webkitURL).

// IE不支持,其他浏览器也有版本要求
let url = new URL("http://foo:bar@localhost:8088/one.html?a=1&b=2")

// 在chrome中测试
url.username	// foo, 没有则为empty string
url.password	// bar, 没有则为empty string

url.URLSearchParams		// URLSearchParams实例,只读

// 其他properties同location,没有methods

3 URLSearchParams Interface

The URLSearchParams interface defines utility methods to work with the query string of a URL.

  • Constructor
// 注意:IE不支持,其他浏览器也要求较高版本,所有methods都是Experiment APIs
// 以下方法等价
let s = new URLSearchParams("?a=1&b=2")		// 最前面的?会被忽略
let s = new URLSearchParams("a=1&b=2")
let s = new URLSearchParams([["a", 1], ["b", 2]])
let s = new URLSearchParams({a: 1, b: 2})
  • Methods
s.has("a")		// true
s.forEach((v, k, o) => console.log(v, k, o))
// 1 a s, 2 b s

s.append("a", 11)
s.get("a")		// 1, 返回第一个,没有则返回null
s.getAll("a")	// [1, 11]

// 返回Iterator对象
[...s.keys()]		// ["a", "b", "a"]
[...s.values()]		// [1, 2, 11]
[...s.entries()]	// [["a", 1], ["b", 2], ["a", 11]]

s.sort()	// 按key升序排序
[...s.keys()]		// ["a", "a", "b"]

s.set("c", 3)	// 相当于append
s.set("a", 1)	// 只剩下一个"a"
[...s.keys()]		// ["a", "b"]
s.delete("a")	// 删除所有的"a"

参考:
https://developer.mozilla.org/en-US/docs/Web/API/location
https://developer.mozilla.org/en-US/docs/Web/API/URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

猜你喜欢

转载自blog.csdn.net/u014711094/article/details/83047450
今日推荐