爱游戏手机登录入口_爱游戏(中国)

爱游戏手机登录入口_爱游戏(中国)

全国热线:400-660-5510广州:020-22265510深圳:0755-23915687上海:021-32265355
site topic网站专题
爱游戏手机登录入口_爱游戏(中国)
>
网站专题
>
专题详情
分享新闻到:

在HTML中获取正确的URL属性值

爱游戏手机登录入口_爱游戏(中国) :2009-11-01 00:00     阅读数:       标签:

在HTML中,常见的URL有多种表示方式:

相对URL:

以下为引用的内容:

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


绝对URL:

以下为引用的内容:

    //dancewithnet.com/example.php
    //dancewithnet.com:80/example.php
    //dancewithnet.com/example.php


同时HTML中有大量的元素属性值为URL,一般利用JavaScript获取这些URL属性值有两种方法:

以下为引用的内容:

<a href=//www.chinaz.com/Design/Pages/"example.php" id="example-a">此时页面绝对URL是//dancewithnet.com/</a>
<script>
var oA = document.getElementById('example-a');
oA.href =//www.chinaz.com/Design/Pages/= '//dancewithnet.com/example.php';
oA.getAttribute('href') == 'example.php';
</script>


爱游戏手机登录入口_爱游戏(中国) 希望通过直接访问属性的方式得到完整绝对URL,通过getAttribute方法得到其原始的属性值,实际上这是一个比较理想的结果,在所有的A级浏览器中,能顺利得到这个结果的只有Firefox和IE8,其他浏览器都或多或少特殊情况,具体哪些元素的属性存在什么样的情况请看 。

在大部分浏览器中存在的问题是,两种方式都返回的是原始属性值,而实际应用中往往需要的是其绝对的URL,《》中的解决方案太过于复杂,这里提供一种相对简单的解决方案,如果不考虑区别浏览器代码会非常简单:

以下为引用的内容:

<form action="example.php" id="example-form">
此时页面绝对URL是//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') == '//dancewithnet.com/example.php';

getQualifyURL = function(oEl,sAttr){
  var sUrl = oEl[sAttr],
      oD,
      bDo = false;
  //是否是IE8之前版本
  ////www.thespanner.co.uk/2009/01/29/detecting-browsers-javascript-hacks/
  ////msdn.microsoft.com/en-us/library/7kx09ct1%28VS.80%29.aspx
  可以解决这个问题,同时还可以对IFEAM和LINK元素解决前面提到的两种方法都返回原始属性的问题:

以下为引用的内容:

<link href=//www.chinaz.com/Design/Pages/"../../example.css" id="example-link">
<a href=//www.chinaz.com/Design/Pages/"example.php" id="example-a">此时页面绝对URL是//dancewithnet.com/</a>

<script>
var oA = document.getElementById('example-a'),
     oLink = document.getElementById('example-a');

oA.href =//www.chinaz.com/Design/Pages/= '//dancewithnet.com/example.php';
oA.getAttribute('href') == '//dancewithnet.com/example.php';
oA.getAttribute('href',2) == 'example.php';

oLink.href =//www.chinaz.com/Design/Pages/= 'example.php';
oLink.getAttribute('href') == 'example.php';
oLink.getAttribute('href',4) == '//dancewithnet.com/example.php';
</script>

原文:

本文链接: