在html中,常見的url有多種表示方式:
相對url:
example.php
demo/example.php
./example.php
../../example.php
/example.php
絕對url:
http://dancewithnet.com/example.php
http://dancewithnet.com:80/example.php
https://dancewithnet.com/example.php
同時html中有大量的元素屬性值為url,一般利用javascript獲取這些url屬性值有兩種方法:
<a href="example.php" id="example-a">此時頁面絕對url是http://dancewithnet.com/</a>
<script>
var oa = document.getelementbyid('example-a');
oa.href == 'http://dancewithnet.com/example.php';
oa.getattribute('href') == 'example.php';
</script>
我們希望通過直接訪問屬性的方式得到完整絕對url,通過getattribute方法得到其原始的屬性值,實際上這是一個比較理想的結果,在所有的a級瀏覽器中,能順利得到這個結果的只有firefox和ie8,其他瀏覽器都或多或少特殊情況,具體哪些元素的屬性存在什么樣的情況請看 演示實例 。
在大部分瀏覽器中存在的問題是,兩種方式都返回的是原始屬性值,而實際應用中往往需要的是其絕對的url,《dealing with unqualified href values》中的解決方案太過于復雜,這里提供一種相對簡單的解決方案,如果不考慮區別瀏覽器代碼會非常簡單:
<form action="example.php" id="example-form">
此時頁面絕對url是http://dancewithnet.com/</form>
<script>
var oform = document.getelementbyid('example-form');
//ie6、ie7、safari、chrome、opera
oform.action == 'example.php';
oa.getattribute('action') == 'example.php';
//獲取絕對url的通用解決方案
getqualifyurl(oform,'action') == 'http://dancewithnet.com/example.php';
getqualifyurl = function(oel,sattr){
var surl = oel[sattr],
od,
bdo = false;
//是否是ie8之前版本
//http://www.thespanner.co.uk/2009/01/29/detecting-browsers-javascript-hacks/
//http://msdn.microsoft.com/en-us/library/7kx09ct1%28vs.80%29.aspx
/*@cc_on
try{
bdo = @_jscript_version < 5.8 ?true : @false;
}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');
/*
//dom 操作得到的結果不會改變
var oa = document.createelement('a');
oa.href = oel[sattr];
od.appendchild(oa);
*/
od.innerhtml = ['<a href="',surl,'"></a>'].join('');
surl = od.firstchild.href;
}
return surl;
}
</script>
在ie6和ie7這兩個史前的瀏覽器身上還有一些更有意思的事情,兩種方法在html元素a、area和img獲取的屬性值都是絕對url,幸好 微軟為getattribute提供了第二個參數 可以解決這個問題,同時還可以對ifeam和link元素解決前面提到的兩種方法都返回原始屬性的問題:
<link href="../../example.css" id="example-link">
<a href="example.php" id="example-a">此時頁面絕對url是http://dancewithnet.com/</a>
<script>
var oa = document.getelementbyid('example-a'),
olink = document.getelementbyid('example-a');
oa.href == 'http://dancewithnet.com/example.php';
oa.getattribute('href') == 'http://dancewithnet.com/example.php';
oa.getattribute('href',2) == 'example.php';
olink.href == 'example.php';
olink.getattribute('href') == 'example.php';
olink.getattribute('href',4) == 'http://dancewithnet.com/example.php';
</script>
新聞熱點
疑難解答