js获取地址栏各种值

获取地址栏参数值
http://www.xxx.com/index.html?ver=1.0&id=6#page1

    function getQueryVariable(variable) {//获取参数id
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){return pair[1];}
        }
        return(false);
    }

getQueryVariable(ver) // 1.0
getQueryVariable(id) // 6

我们可以用javascript获得其中的各个部分
1、整个URl字符串(在浏览器中就是完整的地址栏http://www.xxx.com/index.html?ver=1.0&id=6#page1)
本例返回值: (http://www.xxx.com/index.html?ver=1.0&id=6#page1)

window.location.href

2、URL 的协议部分 (http://www.xxx.com/index.html?ver=1.0&id=6#page1)
本例返回值:http:

window.location.protocol

3、URL 的主机部分 (http://www.xxx.com/index.html?ver=1.0&id=6#page1)
本例返回值:www.xxx.com

window.location.host

4、URL 的端口部分 ( http:192.168.1.152:8080/index.html)
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:"8080"

window.location.port

5、URL 的路径部分(http://192.168.1.145/community/page/index.html?categoryId=#page3)
本例返回值:/community/page/index.html

window.location.pathname

6、查询(参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?ver=1.0&id=6

window.location.search

7、锚点 (http://192.168.1.145/community/page/index.html?categoryId=#page3)
本例返回值:#page3

window.location.hash
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容