DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
HTML 中的 URL 寫法:相對路徑、絕對路徑與 JS 取值差異
編輯:HTML和Xhtml     

URL 在 HTML 裡有各種寫法,而 JavaScript 讀取這些屬性時,各瀏覽器的行為還不一致。搞不清楚這件事,很容易在跨瀏覽器開發時踩坑。

常見的兩類寫法

相對 URL:

example.php
demo/example.php
./example.php
../../example.php
/example.php

絕對 URL:

https://jb51.net/example.php
https://jb51.net:80/example.php
https://jb51.net/example.php

用 JavaScript 取值的兩種方式

HTML 中有大量屬性的值本身就是 URL。取得這些值有兩種途徑:

<a href="example.php" id="example-a">此時頁面絕對 URL 是 https://jb51.net/</a>
<script>
var oA = document.getElementById('example-a');
oA.href == 'https://jb51.net/example.php';        // 直接存取屬性:完整絕對 URL
oA.getAttribute('href') == 'example.php';        // getAttribute:原始屬性值
</script>

理想結果正是如此:直接存取屬性拿到完整絕對 URL,getAttribute 拿到原始寫法。但在當時的 A 級瀏覽器中,只有 Firefox 與 IE8 能穩定做到這點,其餘或多或少都有特殊行為。

多數瀏覽器的共同問題是:兩種方式都只回傳原始屬性值,而實務上我們往往需要的正是絕對 URL。

一個相對簡易的通用解法

先看看 form 的 action 這類屬性:

<form action="example.php" id="example-form">
此時頁面絕對 URL 是 https://jb51.net/</form>
<script>
var oForm = document.getElementById('example-form');
// IE6、IE7、Safari、Chrome、Opera
oForm.action == 'example.php';
oForm.getAttribute('action') == 'example.php';

// 取得絕對 URL 的通用方案
getQualifyURL(oForm, 'action') == 'https://jb51.net/example.php';

getQualifyURL = function(oEl, sAttr){
  var sUrl = oEl[sAttr], oD, bDo = false;
  /*@cc_on
  try{
    bDo = @_jscript_version < 5.8 ? true : @false;   // 是否 IE8 之前版本
  }catch(e){ bDo = false; }
  @*/
  // 是否為 Safari、Chrome、Opera
  if(/a/.__proto__=='//' || /source/.test((/a/.toString+''))
     || /^function \(/.test([].sort)){
    bDo = true;
  }
  if(bDo){
    oD = document.createElement('div');
    oD.innerHTML = ['<a href="', sUrl, '"></a>'].join('');
    sUrl = oD.firstChild.href;
  }
  return sUrl;
}
</script>

思路是借用瀏覽器自己解析 <a> 的能力,把相對路徑轉成絕對路徑,避開一堆手動拼接基準 URL 的麻煩。

IE6 與 IE7 的額外插曲

在這兩個「史前」瀏覽器上還有一層轉折:兩種方式在 A、AREA、IMG 元素上取到的屬性值都是絕對 URL。所幸微軟為 getAttribute 提供了第二個參數可以指定取值模式,同時也順便解決了 IFRAME 與 LINK 元素兩種方法都回傳原始值的問題:

<link href="../../example.css" id="example-link">
<a href="example.php" id="example-a">此時頁面絕對 URL 是 https://jb51.net/</a>
<script>
var oA = document.getElementById('example-a'),
    oLink = document.getElementById('example-link');
oA.href == 'https://jb51.net/example.php';
oA.getAttribute('href') == 'https://jb51.net/example.php';
oA.getAttribute('href', 2) == 'example.php';
oLink.href == 'example.php';
oLink.getAttribute('href') == 'example.php';
oLink.getAttribute('href', 4) == 'https://jb51.net/example.php';
</script>

總結一句:寫跨瀏覽器程式時,不要假設 href 與 getAttribute('href') 在所有環境下都回傳同樣的東西,最好一律走同一個轉絕對路徑的函式。

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