您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 昌吉分类信息网,免费分类信息发布

javascript将相对路径转绝对路径示例_基础知识

2024/4/15 19:41:12发布12次查看
这里介绍的其实本质上是两种方法,通过创建dom或通过javascript计算:
1)通过新创建的image, 经测试会发送一个aborted的请求,并且ie6不支持, 将new image改成document.createelement('img')也是一样的;测试应该不喜欢这个方案;
复制代码 代码如下:
function getabsoluteurl(url){
    var img = new image();
    img.src = url;  // 设置相对路径给image, 此时会发送出请求
    url = img.src;  // 此时相对路径已经变成绝对路径
    img.src = null; // 取消请求
    return url;
}
getabsoluteurl(showroom/list);
2)创建anchor(链接),这种方法不会发出任何请求(请求会在加入dom时产生),但是ie6也不支持
复制代码 代码如下:
/*jslint regexp: true, white: true, maxerr: 50, indent: 2 */
function parseuri(url) {
  var m = string(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\s]*)?/);
  // authority = '//' + user + ':' + pass '@' + hostname + ':' port
  return (m ? {
    href     : m[0] || '',
    protocol : m[1] || '',
    authority: m[2] || '',
    host     : m[3] || '',
    hostname : m[4] || '',
    port     : m[5] || '',
    pathname : m[6] || '',
    search   : m[7] || '',
    hash     : m[8] || ''
  } : null);
}
function absolutizeuri(base, href) {// rfc 3986
function removedotsegments(input) {
    var output = [];
    input.replace(/^(\.\.?(\/|$))+/, '')
         .replace(/\/(\.(\/|$))+/g, '/')
         .replace(/\/\.\.$/, '/../')
         .replace(/\/?[^\/]*/g, function (p) {
      if (p === '/..') {
        output.pop();
      } else {
        output.push(p);
      }
    });
    return output.join('').replace(/^\//, input.charat(0) === '/' ? '/' : '');
  }
href = parseuri(href || '');
  base = parseuri(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
         (href.protocol || href.authority ? href.authority : base.authority) +
         removedotsegments(href.protocol || href.authority || href.pathname.charat(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastindexof('/') + 1) + href.pathname) : base.pathname)) +
         (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
         href.hash;
}
因我们的产品为手机端网页,早已不支持ie6,最终使用的是第二种方案;由此可见,用原生态的方法访问所有的image, anchor时,返回的都是绝对路径,此时如果想返回原来的相对路径,可以用查询dom的方法,如jquery.attr()方法:
复制代码 代码如下:
//返回绝对路径,jquery对象实质上是类数组结构(类似arguments),因此使用[0]可以访问到原生态的对象,然后取href;
console.log($anchor[0][href]);
//返回原始路径
console.log($anchor.attr(href));
昌吉分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录