01 五月 2009 @ 4:26 上午 
做專案時常常因為路徑問題而困擾,因為現在用的路徑很可能到另一個環境就有大幅度的變動,寫前端程式的時候更常遇到這個問題,當然每個人都會把路徑獨立出來成一個變數,到時候若要改的話只要改個變數即可,但像CSS的url command就可以讀相對路徑,因此路徑只要指向相對路徑即可,就算環境換了也不用改任何程式。因此如果每一隻script都可以知道自己被include的Root路徑,需要指定路徑的地方就只要根據這個Root路徑來做相對路徑即可。例如一隻js檔裡頭需要動態產生圖片,那麼就會需要用到這個相對路徑。
var SCRIPTROOTSRC = (function(){
 var RELATIVE = /^[\w\.]+[^:]*$/;
 function makePath(href, path) {
 if (RELATIVE.test(href)) href = (path || "") + href;
 return href;
 };

 function getPath(href, path) {
 href = makePath(href, path);
 return href.slice(0, href.lastIndexOf("/") + 1);
 };

 // get the path to this script
 var scripts = document.getElementsByTagName('script');
 var script = scripts[scripts.length - 1];
 var path = getPath(script.src);
 return path;
})();
alert(SCRIPTROOTSRC);
程式很簡單,只要執行時取得document.getElementsByTagName(‘script’)的最後一個,就是指向目前這隻script,分析自己的src就會知道路徑,再用Regular Expression來取得root。 既然知道root,就可以用SCRIPTROOTSRC來做相對路徑了。 唯一需要注意的地方,如果有好幾隻script的話,請把SCRIPTROOTSRC包在物件裡頭使用,或是自己取別的名稱吧!
Posted By: BLACKBING
Last Edit: 01 五月 2009 @ 04:26 上午

EmailPermalink
Tags


 

Responses to this post » (None)

 
Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


 Last 50 Posts
 Back
Change Theme...
  • Users » 30
  • Posts/Pages » 64
  • Comments » 35
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

About Me



    No Child Pages.

留言板



    No Child Pages.

Album



    No Child Pages.