zoukankan      html  css  js  c++  java
  • 小技巧之a标签自动解析URL

    我们可能都知道javascript中的window.location对象用来获取当前页面的地址URL,并把浏览器重定向到新的页面。它有protocol、hostname、host、port、search、hash、href、pathname等属性

    比如:

    window.location.href返回的是当前页面的整个URL

    window.location.hostname返回的是web主机的域名

    window.location.pathname返回的是当前页面的路径和文件名

    还有一个window.location.assign()方法,传入的是一个URL地址,用来加载新的文档。

    很少人会知道的是a标签也和window.location一样也有这样属性,可以方便我们分析网址。因为html中的<a>标签每出现一次,就会创建一个Anchor对象

    代码如下:

    function parseURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return {
    source: url,
    protocol: a.protocol.replace(':',''),
    host: a.hostname,
    port: a.port||'80',
    query: a.search,
    params: (function(){
    var ret = {},
    seg = a.search.replace(/^?/,'').split('&'),
    len = seg.length, i = 0, s;
    for (;i<len;i++) {
    if (!seg[i]) { continue; }
    s = seg[i].split('=');
    ret[s[0]] = s[1];
    }
    return ret;
    })(),
    file: (a.pathname.match(//([^/?#]+)$/i) || [,''])[1],
    hash: a.hash.replace('#',''),
    path: a.pathname.replace(/^([^/])/,'/$1'),
    relative: (a.href.match(/tps?://[^/]+(.+)/) || [,''])[1],
    segments: a.pathname.replace(/^//,'').split('/')
    };
    }
  • 相关阅读:
    js中的数据类型和判断数据类型
    MVC,MVVM,MVP等设计模式的分析
    mvc框架详解
    插件推荐系列
    响应式区间
    js短路原理:&&, ||
    不错的表单样式
    测试ip
    Python模拟登陆万能法
    iphone 端 ipunt输入框光标偏移
  • 原文地址:https://www.cnblogs.com/luoqian/p/5901780.html
Copyright © 2011-2022 走看看