getBaseURL()在href =""中的javascript调用函数

meo*_*hmy 15 javascript function

我在html页面中通过javascript调用基于URL的URL,我想添加基本URL来调用链接

例如.

<a href="getBaseURL()/filepath/index.html">Page</a>
Run Code Online (Sandbox Code Playgroud)

javascript如下:

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));

    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}
Run Code Online (Sandbox Code Playgroud)

编辑

它只是从相关域获取任何基本URL.另外,我从教程中获得了这些代码,因此任何需要较少处理的建议都将非常感谢

第二次编辑

嗨所有感谢您的答案到目前为止,但是,我希望将函数调用到html标记,如<a href="getURL()/filepath/file.html></a>.这就是问题所在,我不确定如何做到这一点

Cri*_*hez 30

function getBaseURL () {
   return location.protocol + "//" + location.hostname + 
      (location.port && ":" + location.port) + "/";
}
Run Code Online (Sandbox Code Playgroud)

编辑:解决Mike Samuel关于非标准端口的观点.

  • 也许你对常见环境的断言是正确的,但是在没有警告的情况下在帮助论坛上提供简化的代码是不好的做法.如果您知道它在某些情况下失败,请在评论中提及.每个目录,`http:// example.com/foo/bar.html`的基本URL(没有来自`<base>`的覆盖)是`http:// example.com/foo /`,而不是`http :// example.com /`. (3认同)
  • 如果路径中有多个目录级别的路径,非标准端口或文档中的`<base href = ...>`元素,那么这是错误的. (2认同)

Hor*_*Kol 5

允许使用<base>(或不使用)的一般解决方案- 进一步改进是使用某种正则表达式从baseURL中删除baseDocument.

function getBaseURL () {
    var baseURL = "";
    var baseDocument = "index.html";

    if (document.getElementsByTagName('base').length > 0) {
        baseURL = document.getElementsByTagName('base')[0].href.replace(baseDocument, "");
    } else {
        baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
    }

    return baseURL;
}
Run Code Online (Sandbox Code Playgroud)