getBaseURL() javascript call function in a href=""
getBaseURL() javascript call function in a href=""
我在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)。
相关文章:
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- 如何提取“;href"最近列表项中的属性值
- CKEditor如何允许href="javascript:void(0)"在小部件中
- 如何使用Javascript获取当前页面URL,并在<a href="[the_URL]”>
- JSP<a href="">无法保存常规语句
- jQuery:使用.attr('href',")调用javascript
- Linkify/Clickable Text URL,但忽略那些已经包装在“;a href"'s
- 阻止href="#"链接更改URL哈希
- a href="上的javascript对象对象;javascript:"呼叫
- "href"JavaScript Android中的链接不起作用
- 菜单href="#pannel”;不适用于android
- 参考“;href"而不是html中锚点标签中的url
- 更改URL而不使用<a href="">
- 冷融合:空链接href="#"错误
- 如何检查带有href="某事“;与Jquery有一定的类
- 突出显示菜单中具有href="#"“选项”;a“;标签
- jQuery替换所有href=""其中onclick=“;window.location=“;
- <a href="#">最终调用Javascript函数
- 命令“;window.location.href"不适用于HTML(引导框架)
- href对页面的HTML调用"UP”;目录