JavaScript獲取當(dāng)前url根目錄(路徑)
主要用到Location 對象,包含有關(guān)當(dāng)前 URL 的信息,是 Window 對象的一個部分,可通過 window.location 屬性來訪問。
方法一、js獲取項目根路徑的方法
function getRootPath(){ var curPageUrl = window.document.location.href; var rootPath = curPageUrl.split("http://")[0] + curPageUrl.split("http://")[1].split("/")[0] + curPageUrl.split("http://")[1].split("/")[1]; return rootPath; }
方法二 (window.document.location.href/window.document.location.pathname) ------------轉(zhuǎn)自網(wǎng)絡(luò)
function getRootPath_web() { //獲取當(dāng)前網(wǎng)址,如: http://localhost:8083/uimcardprj/share/meun.jsp var curWwwPath = window.document.location.href; //獲取主機地址之后的目錄,如: uimcardprj/share/meun.jsp var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); //獲取主機地址,如: http://localhost:8083 var localhostPaht = curWwwPath.substring(0, pos); //獲取帶"/"的項目名,如:/uimcardprj var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); return (localhostPaht + projectName); }
方法三(window.location.pathname/window.location.protocol/window.location.host)
function getRootPath_dc() { var pathName = window.location.pathname.substring(1); var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/')); if (webName == "") { return window.location.protocol + '//' + window.location.host; } else { return window.location.protocol + '//' + window.location.host + '/' + webName; } }
注:
1、document默示的是一個文檔對象,window默示的是一個窗口對象,一個窗口下可以有多個文檔對象。
所以一個窗口下只有一個window.location.href,然則可能有多個document.URL、document.location.href------------轉(zhuǎn)自網(wǎng)絡(luò)
2、window.location.href和document.location.href可以被賦值,然后跳轉(zhuǎn)到其它頁面,document.URL只能讀不克不及寫------------轉(zhuǎn)自網(wǎng)絡(luò)
3、Location 對象詳細信息參考w3school http://www.dbjr.com.cn/w3school/jsref/dom_obj_location.htm
腳本之家小編補充:
排除某些目錄的廣告實現(xiàn)
var pathName = window.document.location.pathname; var projectName = pathName.substring(1, pathName.substr(1).indexOf('/') + 1); var ad_projectlist = ',,web,html5,css,'; if(ad_projectlist.indexOf(','+projectName+',') < 0){ alert("web,html5,css幾個目錄代碼不執(zhí)行"); }
以上就是本文的全部內(nèi)容,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript比較當(dāng)前時間是否在指定時間段內(nèi)的方法
這篇文章主要介紹了JavaScript比較當(dāng)前時間是否在指定時間段內(nèi)的方法,涉及javascript時間與字符串的轉(zhuǎn)換及比較操作相關(guān)技巧,需要的朋友可以參考下2016-08-08JavaScript?數(shù)據(jù)結(jié)構(gòu)之集合創(chuàng)建(2)
這篇文章主要介紹了JavaScript?數(shù)據(jù)結(jié)構(gòu)之集合創(chuàng)建,上一篇我們介紹了什么是集合,并且手動實現(xiàn)了一個集合的類,本篇基于上篇內(nèi)容繼續(xù)深入介紹需要的小伙伴可以參考一下2022-04-04微信小程序開發(fā)之從相冊獲取圖片 使用相機拍照 本地圖片上傳
本篇文章主要介紹了微信小程序開發(fā)之從相冊獲取圖片--使用相機拍照,本地圖片上傳的相關(guān)資料。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04