从链接的href属性获取完整的URI

Sav*_*man 24 javascript hyperlink

我想在某些方面得到确认.

我的目标是在从链接读取href属性时始终获取相同的字符串(在我的情况下是URI).例:

<a href="test.htm" />with base_url = http://domain.name/

<a href="../test.htm" />with base_url = http://domain.name/domain/

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

我需要http://domain.name/test.htm从上面的3种情况(或任何其他相同的字符串)中获得.

经过一些测试后,似乎 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.

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

Mar*_*aio 23

是的,你可以信赖!

有一次,当人们使用简单的javascript(没有jQuery)时,许多人问你要求的相反,他们想要得到href属性中写的真实url而不是完整的url,在这种情况下他们曾经只是这样做:

my_a_dom_node.getAttribute('href', 2); //works both IE/FF
Run Code Online (Sandbox Code Playgroud)

然后是jQuery帮助人们不要浪费时间发现他们需要这样的代码,jQuery总是返回href属性中写的真实url.

有趣的是,现在有人问如何获取完整的URL,因为jQuery返回了href属性中写的那个.


小智 14

我知道这是一个老问题,但这实际上是第一个出现的条目,我相信添加额外的解决方案是件好事.自从jQuery引入了"prop"功能以来,获取完整的URL非常简单:

$(my_a_dom_node).prop('href');
Run Code Online (Sandbox Code Playgroud)

我希望这仍然有助于某人.


Tom*_*lak 10

是的,你可以依靠这个.

通过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;    
  }
});
Run Code Online (Sandbox Code Playgroud)

因此,它有效地调用elem.getAttribute('href')返回实际属性值,而href属性设计返回规范URL.

但是,有一个参考jQuery.support.hrefNormalized,jQuery支持网站必须说:

  • hrefNormalized:如果.getAttribute()方法检索href元素的属性不变,则等于true ,而不是将其规范化为完全限定的URL.(目前在IE中它是假的,URL被标准化).DOM l3规范

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