Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - Get the full URI from the href property of a link

I would like to have a confirmation on some point.

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:

<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 = any folder from http://domain.name/

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

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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

YES, you can rely!

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...