DIV CSS 佈局教程網

用 JavaScript 取得 Web 應用程式根目錄路徑
編輯:JavaScript綜合知識     

在前端開發中,常有需要動態取得網站根目錄的需求,例如拼接靜態資源路徑或 API 位址。以下是一個簡短而實用的寫法。

實作程式碼

<script>
function getRootPath() {
  var strFullPath = window.document.location.href;
  var strPath = window.document.location.pathname;
  var pos = strFullPath.indexOf(strPath);
  var prePath = strFullPath.substring(0, pos);
  var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
  return prePath + postPath;
}

var webpath = getRootPath();   // webpath 即為根目錄路徑
</script>

原理說明

做法是先取出完整的網址與路徑部分,用 indexOf 找出路徑在完整網址中的起始位置,切出前面的「通訊協定+網域」片段;再從路徑中取出第一層目錄名稱,兩段拼接起來就是應用程式的根路徑。

使用時機

在頁面可能被部署到虛擬目錄的情況下,寫死絕對路徑容易出錯,用這種動態計算的方式會更有彈性。不過若只是單純引用同目錄資源,直接用相對路徑通常就足夠了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved