咱们以http://www.example.com:8989/test/index.html#box?username=yxw&age=11为当前页面的URL
获取当前页面的URL: location.href
location除了href属性以外,还有如下几个属性
咱们的URL大致能够分为一下几个部分html
属 性 名 | 例 子 | 说 明 |
---|---|---|
protocol | 'http' | 返回页面使用的协议。一般是http:或https: |
hostname | 'www.example.com' | 返回不带端口号的服务器名称 |
host | 'www.example.com:8989' | 返回服务器名称和端口号(若有端口号则返回,不然不返回端口号) |
port | '8989' | 返回URL中指定的端口号,若是URL中不包含端口号, 则这个属性返回空字符串 |
pathname | '/test/index.html' | 返回URL中的目录和(或)文件名 |
hash | '#box' | 返回URL中hash(锚点连接,#后面跟零或多个字符), 若是URL中不包含,则返回空字符串 |
search | '?username=yxw&age=11' | 返回URL的查询字符串,这个字符串以问号(?)开头 |
var brand=location.hostname.split('.')[1]; console.log(brand) //'example'
function getQueryStringArgs() { //取得查询字符串并去掉开头问号 var qs = (location.search.length > 0 ? location.search.substring(1) : ''); // 保存数据的对象 var args = {}; // 取得每一项 var items = qs.length ? qs.split('&') : []; var item = null, name = null, value = null; //逐个将每一项添加到args对象中 for (var i = 0; i < items.length; i++) { item = items[i].split('='); name = decodeURIComponent(item[0]); value = decodeURIComponent(item[1]); if (name.length) { args[name] = value; } } return args; } args=getQueryStringArgs(); console.log(args['username']) //yxw