打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
BOM location对象详解

文章目录

location对象

location对象是window对象下的一个属性,用的时候可以省略window对象

location可以获取或者设置浏览器地址栏的URL

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>title</title>
  <script>

    //对象中的属性和方法
    //location对象
    console.log(window.location);

   //地址栏上#及后面的内容
   console.log(window.location.hash);
   //主机名及端口号
   console.log(window.location.host);
   //主机名
   console.log(window.location.hostname);
   //文件的路径---相对路径
   console.log(window.location.pathname);
   //端口号
   console.log(window.location.port);
   //协议
   console.log(window.location.protocol);
   //搜索的内容
   console.log(window.location.search);

    onload=function () {
      document.getElementById("btn").onclick=function () {
        // 设置跳转的页面的地址
       location.href="http://www.jd.com";//属性----------------->必须记住
       location.assign("http://www.jd.com");//方法
        location.reload();//重新加载--刷新
        location.replace("http://www.jd.com");//没有历史记录
        
      };
    };

  </script>
</head>
<body>
<input type="button" value="显示效果" id="btn"/>

</body>
</html>

URL

统一资源定位符 (Uniform Resource Locator, URL)

  • URL的组成
scheme://host:port/path?query#fragment
scheme:通信协议
常用的http,ftp,maito等
host:主机
服务器(计算机)域名系统 (DNS) 主机名或 IP 地址。
port:端口号
整数,可选,省略时使用方案的默认端口,如http的默认端口为80。
path:路径
由零或多个'/'符号隔开的字符串,一般用来表示主机上的一个目录或文件地址。
query:查询
可选,用于给动态网页传递参数,可有多个参数,用'&'符号隔开,每个参数的名和值用'='符号隔开。例如:name=zs
fragment:信息片断
字符串,锚点.

location有哪些成员?

  • 使用chrome的控制台查看

  • 查MDN

    MDN

  • 成员

    • assign()/reload()/replace()
    • hash/host/hostname/search/href……

案例

解析URL中的query,并返回对象的形式

function getQuery(queryStr) {
  var query = {};
  if (queryStr.indexOf('?') > -1) {
    var index = queryStr.indexOf('?');
    queryStr = queryStr.substr(index + 1);
    var array = queryStr.split('&');
    for (var i = 0; i < array.length; i++) {
      var tmpArr = array[i].split('=');
      if (tmpArr.length === 2) {
        query[tmpArr[0]] = tmpArr[1];
      }
    }
  }
  return query;
}
console.log(getQuery(location.search));
console.log(getQuery(location.href));
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Node
JS 数组转对象 对象转数组 对象数组互相转换 数组对象互相转换
从零开始学习3D可视化之获取对象
WPS JS宏入门案例集锦
ES6新特性(8)之Decorator修饰器/二进制数组
14万字 | 400多道JavaScript 面试题及详细答案(建议收藏)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服