最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get full URL from a hyperlink using jQueryJavaScript - Stack Overflow

programmeradmin3浏览0评论

How can I retrieve the full URL to which an anchor links using jQuery / JavaScript consistently across all browsers? For example, I want to return .aspx from <a href="../mypage.aspx"></a>.

I have tried the following:

  1. $(this).attr('href'): The problem is that jQuery returns the exact value of the href (i.e., ../mypage.aspx).

  2. this.getAttribute('href'): This works in Internet Explorer, but in FireFox it behaves the same as above.

What is the alternative? I cannot simply append the current site's path to the href value because that would not work in the above case in which the value of the href escapes the current directory.

How can I retrieve the full URL to which an anchor links using jQuery / JavaScript consistently across all browsers? For example, I want to return http://www.mysite./mypage.aspx from <a href="../mypage.aspx"></a>.

I have tried the following:

  1. $(this).attr('href'): The problem is that jQuery returns the exact value of the href (i.e., ../mypage.aspx).

  2. this.getAttribute('href'): This works in Internet Explorer, but in FireFox it behaves the same as above.

What is the alternative? I cannot simply append the current site's path to the href value because that would not work in the above case in which the value of the href escapes the current directory.

Share Improve this question edited Jun 10, 2012 at 15:54 TazGPL 3,7462 gold badges40 silver badges60 bronze badges asked Nov 28, 2011 at 4:50 Devin BurkeDevin Burke 13.8k12 gold badges58 silver badges85 bronze badges 3
  • Possible duplicate of stackoverflow./questions/303956/… – Gilles Quénot Commented Nov 28, 2011 at 4:57
  • You might want to check out this question stackoverflow./questions/470832/… – Brian Fisher Commented Nov 28, 2011 at 5:02
  • 1 @sputnick, it's definitely not a duplicate of that. This looks like your basic n00bert url propery question on the surface, but it's a little more plicated. – Devin Burke Commented Nov 28, 2011 at 5:08
Add a ment  | 

1 Answer 1

Reset to default 6

You can create an img element and then set the src attribute to the retrieved href value. Then when you retrieve the src attribute it will be fully qualified. Here is an example function that I have used from http://james.padolsey./javascript/getting-a-fully-qualified-url/:

function qualifyURL(url){
    var img = document.createElement('img');
    img.src = url; // set string url
    url = img.src; // get qualified url
    img.src = null; // no server request
    return url;
}
发布评论

评论列表(0)

  1. 暂无评论