1. src
//html <script type="text/jvascript" src="ooxx.js"></script> //script var script = document.getElementsByTagName('script')[0]; //標准瀏覽器返回 http://www.ooxx.com/ooxx.js 即返回絕對路徑 //IE67,src的字符串為什么則返回什么,這里是ooxx.js alert(script.src); //無兼容問題,均返回src所填字符串,這里為ooxx.js alert(script.getAttribute('src'));
2. href
//html <a href="ooxx.html">ooxx</a> //script var a = document.getElementsByTagName('a')[0]; //無兼容問題,均返回href的絕對路徑,形如http://www.ooxx.com/ooxx.html alert(a.href); //標准瀏覽器返回相對路徑,即ooxx.html //IE67返回絕對路徑,形如http://www.ooxx.com/ooxx.html alert(a.getAttribute('href');
3. 總結
1. 想獲取script中src的相對路徑,用 script.getAttribute('src')
2. 想獲取script中src的絕對路徑,如下代碼
var src = script.hasAttribute ? script.src : script.getAttribute('src',4);
因為 IE67 不支持hasAttribute方法,故可用其判斷區分;再加上IE對getAttribute支持第2個參數,參數為4時,返回絕對路徑,詳細參數查看http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx
3. 想獲取a中href的相對路徑,用 a.getAttribute('href',2) ,依然是利用IE的專屬參數另其字符串方式返回所要的相對路徑。
4. 想獲取a中href的絕對路徑,用a.href即可。
OVER!