前端基础location的使用

概念

获取当前页面的地址信息,还可以修改某些属性,实现页面跳转和刷新等。

 样例展示

window.location 含义.originURL 基础地址,包括协议名、域名和端口号.protocol协议 (http: 或 https:).host域名+端口号.hostname域名.port端口号.pathname路径(以/开头).search查询字符串,以?开头.hash页面锚点,以#开头.href完整 URL

比较容易混淆的是hosthostname这两个属性,区别是前者还包含了端口号。

修改属性值

以上属性除了origin是只读属性,其他都可以修改。修改后的效果就是跳转到相应的新地址。

属性一览表

方法一览表

.assign()导航到指定 URL.replace()导航到指定 URL并删除当前页面的访问记录.reload()重新加载当前页面.toString()返回 URL 字符串

.toString().href都是返回 URL,它们之间有区别吗?结果是一样的,性能上稍微有点差别。通过 JSPerf 上的性能测试结果可以看出,.href稍快,通过window.location拼接字符串的形式速度最慢。

.assign() 和直接修改href是等价的,那么它们跟.replace()的区别是什么呢?

.assign() 在跳转新地址的同时会留下当前页面的访问记录,点击浏览器返回按钮会回到原来的页面,.replace()则不会保留。

场景1:页面跳转锦集

location.href='https://www.baidu.com'
window.open('http://www.baidu.com','_self')
location.assign('http://www.baidu.com')
location.replace('http://www.baidu.com')
<a href="https://www.baidu.com">跳转</a>
  • 页面中跳转固定的地址
function imitateClick(url){
	  let aEle = document.createElement("a");
	  aEle.setAttribute("href", url);
	  aEle.setAttribute("target", "_blank");
	  aEle.setAttribute("id", "previewJumpEle");
	  // 防止重复添加
	  if (!document.getElementById("previewJumpEle")) {
	    document.body.appendChild(aEle);
	  }
	  // 模拟点击
	  aEle.click();
	  (aEle.remove && aEle.remove()) || (aEle.removeNode && aEle.removeNode(true));
};
imitateClick('https://www.baidu.com');

  • js中直接做无感跳转,但是此方法有个弊端:经过验证,有的浏览器可能会拦截,慎用。

<meta http-equiv="refresh" content="5;url=http://www.w3school.com.cn">

场景2:检测协议并提示用户

if (location.protocol == 'http:') {
      this.$confirm('确定吗?').then(() => {
        location.href = 'https://www.baidu.com'
      })
    }

猜你喜欢

转载自blog.csdn.net/2201_75705263/article/details/135152374