Fork me on GitHub

BOM元素之location对象

location对象提供了与当前窗口中加载的文档有关的信息,还提供了一些导航功能,它既是window对象的属性,也是document对象的属性;换句话说,window.location和document.location引用的是同一个对象

 

在location对象的属性中我觉得最有用的是可以用search查询浏览器发送过来的请求参数,但是通过这样获得的请求参数并不是我们最终想得到的请求参数,但是我们可以通过以下JavaScript代码来达到转换请求参数格式的目的

window.onload = function () {
        //取得查询字符串,并去掉开头的问号
        var qs = (location.search.length > 0 ? location.search.substring(1) : "");

        //保存数据对象
        args = {};

        //取得每一项
        var items = qs.length ? qs.split("&") : [];

        item = null;
        name = null;
        value = null;

        i = 0;
        len = items.length;

        //逐个将每一项添加到args对象中
        for (i = 0; i<len; i++) {
            item = items[i].split("=");
            name = decodeURIComponent(item[0]);
            value = decodeURIComponent(item[1]);

            if (name.length) {
                args[name] = value;
            }
        }

        console.log(args);
}

 

在location的属性当中,还有一个方法我们应当注意,那就是reload(),区别在于浏览器重新加载的方式:

location.relaod();//有可能从缓存中加载
location.reload(true);//从服务器重新加载

 

 

posted @ 2016-11-25 10:05  阿森丶  阅读(251)  评论(0编辑  收藏  举报