从链接的 href 属性获取完整的 URI [英] Get the full URI from the href property of a link

查看:26
本文介绍了从链接的 href 属性获取完整的 URI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确认一下.

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

My goal is to always get the same string (which is the URI in my case) while reading the href property from a link. Example:

with base_url = http://域名/

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

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

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

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

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

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

I need to get http://domain.name/test.htm from the 3 situations above (or any other identical string).

经过一些测试,my_a_dom_node.href 似乎总是返回完全限定的 URI,包括 http://domaine.name,这对我想要的应该没问题.

After some tests, it appears that my_a_dom_node.href always return the full-qualified URI, including the http://domaine.name, which should be okay for what I want.

jQuery 有不同的行为,$(my_a_dom_node).attr('href') 返回出现在 HTML 中的内容(文本).所以我的技巧是使用 $(my_a_dom_node).get(0).href 来获取完整的 URI.

jQuery has a different behaviour and $(my_a_dom_node).attr('href') returns the content (text) that appears inside the HTML. So my trick is to use $(my_a_dom_node).get(0).href to get the full URI.

问题是:我可以依靠这个吗?

The question is: can I rely on this?

推荐答案

是的,您可以信赖!

曾经当人们使用简单的 javascript(没有 jQuery)时,许多人问的与您所问的相反,他们想获得 href 属性中所写的真实网址,而不是完整的网址,在这种情况下,他们过去常常简单地做:

Once when people was using simple javascript (no jQuery) many asked the opposite of what you are asking, they wanted to get the real url as written in the href attribute and not the full one, in such case they used to simply do:

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

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

Then it came jQuery that helped people not to waste their time in finding out they would need such code and jQuery always returns the real url as written in the href attribute.

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

It's funny that now someone is asking how to get the full url because jQuery returns the one written in the href attribute.

这篇关于从链接的 href 属性获取完整的 URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆