网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 HTML网页中的URL表示方式
内容
    在HTML中,常见的URL有多种表示方式:
    相对URL:
    代码如下:
    example.php
    demo/example.php
    ./example.php
    ../../example.php
    /example.php
    绝对URL:
    代码如下:
    http://jb51.net/example.php
    http://jb51.net:80/example.php
    https://jb51.net/example.php
    同时HTML中有大量的元素属性值为URL,一般利用JavaScript获取这些URL属性值有两种方法:
    代码如下:
    <a href="example.php" id="example-a">此时页面绝对URL是http://jb51.net/</a>
    <script>
    var oA = document.getElementById('example-a');
    oA.href == 'http://jb51.net/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://jb51.net/</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://jb51.net/example.php';
    getQualifyURL = function(oEl,sAttr){
    var sUrl = oEl[sAttr],
    oD,
    bDo = false;
    //是否是IE8之前版本
    ///uploads/202504/02/@cc_onBR    try{BR    bDo3752 = @_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://jb51.net/</a>
    <script>
    var oA = document.getElementById('example-a'),
    oLink = document.getElementById('example-a');
    oA.href == 'http://jb51.net/example.php';
    oA.getAttribute('href') == 'http://jb51.net/example.php';
    oA.getAttribute('href',2) == 'example.php';
    oLink.href == 'example.php';
    oLink.getAttribute('href') == 'example.php';
    oLink.getAttribute('href',4) == 'http://jb51.net/example.php';
    </script>
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/19 23:39:38