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关于非标准端口的观点.
允许使用<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)