代码之家  ›  专栏  ›  技术社区  ›  Savageman

从链接的Href属性获取完整的uri

  •  22
  • Savageman  · 技术社区  · 14 年前

    我想确认一下。

    我的目标是在从链接读取Href属性时始终获得相同的字符串(在我的例子中是uri)。例子:

    <a href="test.htm" /> 带基URL= http://domain.name/

    <a href="../test.htm" /> 带基URL= http://domain.name/domain/

    <a href="http://domain.name/test.htm" /> with base_url=中的任何文件夹 http://domain.name网站/

    我需要得到 http://domain.name/test.htm 以上三种情况(或任何其他相同的字符串)。

    经过一些测试,似乎 my_a_dom_node.href 始终返回完全限定的uri,包括 http://domaine.name ,这应该可以满足我的要求。

    jquery有不同的行为和 $(my_a_dom_node).attr('href') 返回HTML中显示的内容(文本)。所以我的诀窍是 $(my_a_dom_node).get(0).href 获取完整的uri。

    问题是:我能依靠这个吗?

    4 回复  |  直到 8 年前
        1
  •  21
  •   Marco Demaio    12 年前

    是的,你可以信赖!

    有一次,当人们使用简单的javascript(没有jquery)时,许多人问的问题与您的要求相反,他们希望得到在ref属性中写入的真实url,而不是完整的url,在这种情况下,他们只需要做:

    my_a_dom_node.getAttribute('href', 2); //works both IE/FF
    

    然后,jquery帮助人们不浪费时间去发现他们需要这样的代码,jquery总是返回真正的url,如在ref属性中所写的那样。

    有趣的是,现在有人问如何获取完整的url,因为jquery返回了在ref属性中写入的url。

        2
  •  12
  •   arakell    8 年前

    我知道这是个老问题,但这实际上是第一个出现的条目,我相信添加一个额外的解决方案是很好的。自从jquery引入了“prop”函数之后,获取完整的url就变得非常简单:

    $(my_a_dom_node).prop('href');
    

    我希望这对某人还是有帮助的。

        3
  •  10
  •   SilentGhost    14 年前

    是的,你可以相信这一点。

    通过查看jquery(1.4.2)源代码,我看到 jQuery.attr() 正在使用的函数(压缩到相关部分):

    jQuery.extend({
      // ...
      attr: function( elem, name, value, pass ) {
        // ...
    
        var attr = !jQuery.support.hrefNormalized && notxml && special ?
                   // Some attributes require a special call on IE
                   elem.getAttribute( name, 2 ) :
                   elem.getAttribute( name );
    
        // Non-existent attributes return null, we normalize to undefined
        return attr === null ? undefined : attr;    
      }
    });
    

    所以它有效地调用 elem.getAttribute('href') 它返回实际的属性值,而 href 属性按设计返回规范URL。

    但是,有一个参考 jQuery.support.hrefNormalized ,其中jquery支持站点必须声明:

    • hrefNormalized :等于true,如果 .getAttribute() 方法检索 这个 HREF 元素的属性 不变,而不是正常化 到完全限定的url。(它是 当前IE中为False,URL为 标准化)。DOM L3规格

    这基本上意味着jquery自己发现浏览器行为,并相应地进行调整以提供一致的结果。

        4
  •  1
  •   rnaud    14 年前

    您可以使用一点javascript重新组合完整的url:

    function parseLink(link) {
        var baseUrl = location.href.substring(0,location.href.lastIndexOf('/'));
        if (link.indexOf('/') != -1) {
            link = link.substring(link.lastIndexOf('/')); 
        } else {
            link = "/"+ link;
        }
        var fullUrl = baseUrl + link;
        return fullUrl
    }