getBaseURL() javascript call function in a href=""

getBaseURL() javascript call function in a href=""

本文关键字:quot href in javascript call function getBaseURL      更新时间:2023-09-26

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

例如。

<a href="getBaseURL()/filepath/index.html">Page</a>

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 + "/";
    }
}

编辑

它只是从有问题的域中获取任何基本URL。此外,我从一个教程中得到了这段代码,所以任何需要较少处理的建议都会很棒,谢谢

第二版

嗨,非常感谢您到目前为止的回答,不过,我希望像<a href="getURL()/filepath/file.html></a>中那样调用html标记的函数。这就是问题所在,我不确定如何进行

function getBaseURL () {
   return location.protocol + "//" + location.hostname + 
      (location.port && ":" + location.port) + "/";
}

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

允许使用(或不使用)<base>的通用解决方案-进一步的改进是使用某种regex从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;
}

我正在处理同样的问题,与其说是获取基本URL(正如这些答案所示),不如说是从元素中调用javascript函数,然后添加相对路径。使用@Christian Sanchez的答案和我发现的其他信息,这是一个使用元素onclick的选项:

JAVASCRIPT:

<script type="text/javascript">
    function getBaseURL(loc) {
        return location.protocol + "//" + location.hostname +
           (location.port && ":" + location.port) + "/" + loc;
    }
</script>

HTML:

<a href="filepath/index.html" onclick="getBaseURL(this.href);">TEST LINK</a>

Fiddle在这里:http://jsfiddle.net/62g2bkyh/(将鼠标悬停在链接上可以看到fiddle中的URL,它显示了iframe的基本URL)。