简体   繁体   English

如何从没有外部信息的相对网址获取绝对路径?

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

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. 我知道我可以获得window.location,并将其与任何链接的href进行比较,但是有分层文件夹,其中一些文件的命名方式相同,我不能依赖于设置基本服务器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. 基本上我需要将鼠标悬停在链接上时获得的值,并将href属性的所有相关性应用于当前位置。 I'm not really sure how to do that, though. 不过,我真的不知道该怎么做。

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. 它似乎适用于ie8及以上。 ie7 doesnt resolve anything. ie7没有解决任何问题。

*-pike * -pike

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;
}

Not a direct solution for you, but these 2 articles may be helpful: 不是直接的解决方案,但这两篇文章可能会有所帮助:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM