Javascript擷取目前的目錄的絕對路徑方法

來源:互聯網
上載者:User


一談到路徑相關的問題,大家都會往window.location上想,確實這個對象提供了相當多的路徑資訊,其中常用的就包括:

location.href:當前頁面的完整URL
location.pathname:當前URL中的路徑名
location.hash:當前URL中的錨點
location.search:當前URL中的查詢參數

然而,location沒有一個屬效能直接獲得目前的目錄(不含檔案名稱)的絕對路徑。通過Google我發現了一些錯誤的方法,比如說把URL通過“/”分離成數組,把數組的最後一項去掉以後再串連成字串。但如果URL中沒有指定檔案名稱,結果就大錯特錯了。

根據以往編碼的經驗,a元素的href屬性總是會返回絕對路徑,也就是說它具有把相對路徑轉成絕對路徑的能力。使用下面的代碼嘗試了一下,果然成了:

var a = document.createElement('a');a.href = './';alert(a.href);a = null;

很不幸地,此方法在老舊的IE 6/7下無效,當執行alert(a.href)時,彈出的仍然是“./”。後來,我發現在Stackoverflow上也有人提出了這個問題,而解決方案也是很簡單的,只要把a通過innerHTML注入就可以了:

var div = document.createElement('div');div.innerHTML = '<a href="./"></a>";alert(div.firstChild.href);div = null;

有人可能會問:為何不用Regex?我的答案是:要考慮有無檔案名稱的情況、有無錨點的情況、有無查詢參數的情況,這條Regex可能會挺複雜的。

例子

  function getRealPath(){     //擷取當前網址,如: http://localhost:8083/myproj/view/my.jsp      var curWwwPath=window.document.location.href;      //擷取主機地址之後的目錄,如: myproj/view/my.jsp     var pathName=window.document.location.pathname;     var pos=curWwwPath.indexOf(pathName);     //擷取主機地址,如: http://localhost:8083     var localhostPaht=curWwwPath.substring(0,pos);     //擷取帶"/"的項目名,如:/myproj     var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);      //得到了 http://localhost:8083/myproj     var realPath=localhostPaht+projectName;     alert(realPath);   }

例子

這裡給出JavaScript如何獲得檔案的路徑:

function serverMapPath(fileName){var syspath = location.href; syspath = syspath.toLowerCase();      //把路徑名稱轉換成小寫myPosition = syspath.lastIndexOf("/");  // 擷取檔案路徑中的最後一個"/"syspath = syspath.substring(0,parseInt(myPosition)+1); // 使用substring函數 截取"/"之前的字串,就得到目前的目錄的路徑syspath = syspath.replace("file:///","");   //這裡要把file:///替換為空白,否則會報錯syspath = syspath.replace(new RegExp("%20","gm")," ");   // 如果檔案名稱中含有空格,則要還原空格,替換所有的 %20 為 " "syspath = syspath + fileName; return syspath.toString();}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.