[英]getBaseURL() javascript call function in a href=“”
我在html页面中通过javascript调用基于URL的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>
(或不使用)的一般解决方案 - 进一步改进是使用某种正则表达式从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>
小提琴在这里: http : //jsfiddle.net/62g2bkyh/ (将鼠标悬停在链接上以查看小提琴中的URL - 显示iframe的基本URL)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.