DIV CSS 佈局教程網

JavaScript 將相對路徑轉為絕對路徑示例
編輯:JavaScript基礎知識     

這裡介紹的方法本質上有兩種:透過建立 DOM 元素,或透過 JavaScript 計算。

1. 透過新建 Image(實測會發送一個 Aborted 請求,且 IE6 不支援,改用 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]*)?/);
    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 物件本質上是「類陣列」結構,用 [0] 可取到原生物件再取 href)
console.log($anchor[0]["href"]);
// 回傳原始相對路徑
console.log($anchor.attr("href"));
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved