location对象

爷,独闯天下 提交于 2020-03-12 04:20:06

location对象是很特别的一个对象,因为它既是window对象的属性,也是document对象的属性。换句话说,window.location和document.location引用的是同一个对象。这里我们就简单的介绍一下location处理URL片段的方法吧!

一、

 如下每个属性前省去location前缀:

  hash    '#xxxxx'         返回URL中的hash(即#号后面的字符)

  host     'www.baidu.com:80'    返回服务器名称和端口号

  hostname  'www.baidu.com'     返回不带端口号的服务器名称

  href     'http:www.baidu.com'   返回当前加载页面的完整URL,而location对象的toString()方法也返回这个值。

  path     '8080'         返回当前URL的指定的端口号

  pathname   '/xxxx/sssss/'      返回URL中的目录和(或)文件名

  portocol(协议) 'http:'         返回页面使用的协议  http: 或 https: 

  search    '?q=test01'       返回URL的查询字符串。 这个字符串以问号开头

二、

URL查询字符串参数:

  1.获取search

  function getQueryStringArgs () {

    // 获取查询字符并去掉开头的问号

    var searchStr = location.search.length > 0 ? location.search.substring(1) : '',

     // 保存数据的对象

     args = {},

    // 获取每一项参数

    tems = searchStr.length ? searchStr.split('&') : [],

    item = null,

    name = null,

    value = null,

    i = 0,

    len = items.length;

    // 逐个将每一项添加到args对象中

    for (i = 0; i < len; i++) {

      item = items[i].split('=');

      name = decodeURLComponent(item[0]);

      value = decodeURLComponent(item[1]);

     if (name.length) {

      args[name] = value

    }

   }

  }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!