HTMLには、多くの一般的なURLがあります。
相対URL:
example.php
デモ/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には多数の要素属性値があります。一般に、JavaScriptを使用してこれらのURL属性値を取得するには2つの方法があります。
<a href = example.php id = example-a>この時点で、ページは絶対にurl http://dancewithnet.com/ </a>
<スクリプト>
var oa = document.getElementById( 'emple-a');
oa.href == 'http://dancewithnet.com/example.php';
oa.getAttribute( 'href')== 'emple.php';
</script>
属性に直接アクセスして完全な絶対URLを取得し、GetAttributeメソッドを使用して元の属性値を取得したいと考えています。実際、これは比較的理想的な結果です。すべてのAレベルのブラウザの中で、FirefoxとIE8のみがこの結果を正常に取得できます。他のブラウザには多かれ少なかれ特別な状況があります。どの要素がどのような条件を持っているかについては、デモの例を参照してください。
ほとんどのブラウザの問題は、両方のメソッドが元の属性値を返すことですが、実際のアプリケーションでは、必要なのは絶対URLです。 「資格のないHREF値を処理する」のソリューションは複雑すぎます。これが比較的単純なソリューションです。ブラウザコードの違いを考慮しないと、非常に簡単です。
<form action = example.php id = example-form>
この時点で、ページは絶対にurl http://dancewithnet.com/ </form>です
<スクリプト>
var oform = document.getElementById( 'emple-form');
// IE6、IE7、Safari、Chrome、Opera
oform.action == 'embler.php';
oa.getattribute( 'action')== 'emple.php';
//絶対URLを取得する一般的なソリューション
getQualifyurl(oform、 'action')== 'http://dancewithnet.com/example.php';
get qualifyurl = function(oel、attr){
var surl = oel [attr]、
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
試す{
bdo = @_jscript_version <5.8?true:@false;
} catch(e){
bdo = false;
}
@*/
//サファリ、クロム、オペラの場合
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 [attr];
OD.AppendChild(OA);
*/
od.innerhtml = ['<a href ='、surl、 '> </a>'] .join( '');
surl = od.firstchild.href;
}
SURLを返します。
}
</script>
2つの先史時代のブラウザ、IE6とIE7には、さらに興味深いものがいくつかあります。 HTML要素A、領域、およびIMGの2つのメソッドによって取得された属性値は、絶対URLです。幸いなことに、Microsoftはこの問題を解決するためのGetAttributeの2番目のパラメーターを提供し、IFEAMおよびリンク要素の元の属性を返す問題を解決することもできます。
<link href = ../../example.css id = example-link>
<a href = example.php id = example-a>この時点で、ページは絶対にurl http://dancewithnet.com/ </a>
<スクリプト>
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)== 'embler.php';
olink.href == 'example.php';
olink.getAttribute( 'href')== 'emple.php';
olink.getAttribute( 'href'、4)== 'http://dancewithnet.com/example.php';
</script>