1)通過(guò)新創(chuàng)建的Image, 經(jīng)測(cè)試會(huì)發(fā)送一個(gè)Aborted的請(qǐng)求,并且IE6不支持, 將new Image改成document.createElement('IMG')也是一樣的;測(cè)試應(yīng)該不喜歡這個(gè)方案;
代碼如下:
function getAbsoluteUrl(url){
var img = new Image();
img.src = url; // 設(shè)置相對(duì)路徑給Image, 此時(shí)會(huì)發(fā)送出請(qǐng)求
url = img.src; // 此時(shí)相對(duì)路徑已經(jīng)變成絕對(duì)路徑
img.src = null; // 取消請(qǐng)求
return url;
}
getAbsoluteUrl("showroom/list");
2)創(chuàng)建Anchor(鏈接),這種方法不會(huì)發(fā)出任何請(qǐng)求(請(qǐng)求會(huì)在加入DOM時(shí)產(chǎn)生),但是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;
}
因我們的產(chǎn)品為手機(jī)端網(wǎng)頁(yè),早已不支持IE6,最終使用的是第二種方案;
由此可見(jiàn),用原生態(tài)的方法訪問(wèn)所有的Image, Anchor時(shí),返回的都是絕對(duì)路徑,此時(shí)如果想返回原來(lái)的相對(duì)路徑,可以用查詢DOM的方法,如jQuery.attr()方法:
代碼如下:
//返回絕對(duì)路徑,jQuery對(duì)象實(shí)質(zhì)上是"類(lèi)數(shù)組"結(jié)構(gòu)(類(lèi)似arguments),因此使用[0]可以訪問(wèn)到原生態(tài)的對(duì)象,然后取"href";
console.log($anchor[0]["href"]);
//返回原始路徑
console.log($anchor.attr("href"));
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com