How to get absolute path from a relative url with no outside info?

情到浓时终转凉″ 提交于 2020-01-15 02:44:54

问题


I'm trying to dynamically determine whether I'm on a certain page, and set a style on any link linking to itself (for a navigation menu).

The part that's catching me up is how to determine that the page is the current page.

I know I can get window.location, and compare it to the href of any links, but there tiered folders, some of which have files named the same way, and I can't rely on setting a base server url.

Basically I need the value that you get when you hover your mouse over a link, with all the relativity of the href attribute applied to the current location. I'm not really sure how to do that, though.


回答1:


This one works best cross browser

//Resolve absolute url's from relative ones
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;
}



回答2:


based on drew's answer, i tested this

function resolveUrl( url ){
  var a = document.createElement('a');
  a.href=url; // set string url
  url = a.href; // get qualified url
  return url;
}

and it seems to work for ie8 and up. ie7 doesnt resolve anything.

*-pike




回答3:


Not a direct solution for you, but these 2 articles may be helpful:

http://www.phpied.com/relative-to-absolute-links-with-javascript/

Get the full URI from the href property of a link



来源:https://stackoverflow.com/questions/7690784/how-to-get-absolute-path-from-a-relative-url-with-no-outside-info

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!