美文网首页
js获取地址栏各种值

js获取地址栏各种值

作者: YQSummer | 来源:发表于2020-10-22 14:05 被阅读0次

    获取地址栏参数值
    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
    

    相关文章

      网友评论

          本文标题:js获取地址栏各种值

          本文链接:https://www.haomeiwen.com/subject/kcsumktx.html