zoukankan      html  css  js  c++  java
  • 原生JS去解析地址栏的链接?超好用的解决办法

    在做SPA应用程序的时候,往往需要通过地址栏链接的 hash 值来进行业务逻辑:

    <script type="text/javascript">
    //file:///C:/Users/Administrator/Desktop/angularjs/domo/20.ng.html#baidu
    console.log(window.location);
    //结果
    //Location {hash: "#baidu", search: "", pathname: "/C:/Users/Administrator/Desktop/angularjs/domo/20.ng.html", port: "", hostname: ""…}
    </script>

    当页面发生点击,请求发生hash值改变的情况:

    <script type='text/javascript' >
    (function(window){
        window.addEventListener('hashchange',function(e){
            //拿到地址栏的地址
            console.log(window.location.href);
            //拿到地址栏的hash值
            console.log(window.location.hash);
            var oHash = window.location.hash;
            switch(oHash){
                case '#/index/':
                    console.log('index');
                case '#case':
                    console.log('case');
            };
        });
    })(window);
    </script>

    通过 a 链接的方式通过解析地址栏的URL:

    最快捷最方便的方式去解析一个 url 地址,是通过 a 标签的方式去解析

    <script type="text/javascript">
    /*可以通过 window.location 拿到所有URL的所有信息: -->
    //https://www.baidu.com:8080/aaa/1.html?id=10#name
    protocol: https
    host: www.baidu.com:8080
    port: 8080
    pathname: /aaa/1.html
    search: ?id=10
    hash: #name*/
    var url = "https://www.baidu.com:8080/aaa/1.html?id=10#name";
    var aLink = document.createElement('a');
    aLink.href = url;
    //打印出一个标签<a href="https://www.baidu.com:8080/aaa/1.html?id=10#name"></a>
    //使用json遍历(一定是大写的JSON)
    //console.log(JSON.stringify({id:1,name:'张三',age:'18'}));
    //打印出 {"id":1,"name":"张三","age":"18"}
    //JSON 要求键一定是用双引号引起来,json就是一种用字符串描述对象的方式
    console.log(aLink.hostname);
    console.log(aLink.port);
    console.log(aLink.pathname);
    console.log(aLink.search);
    console.log(aLink.hash);
    </script>

    除了 a 标签的解析方法,还有字符串的方法,还有通过正则的方式去解析;

    正则表达式:
    http://tool.oschina.net/regex

  • 相关阅读:
    sql声明变量,及if -else语句、while语句的用法
    视图、事务
    索引
    相关子查询
    递归实现treeView下的省市联动
    创建sqlhelp类以封装对数据库的操作及对可空类型的操作
    ADO.Net操作数据库
    sql的case语句
    vue父组件异步数据子组件接收遇到的坑
    第一次用angularJS做后台管理点滴
  • 原文地址:https://www.cnblogs.com/e0yu/p/7209043.html
Copyright © 2011-2022 走看看