Javascript / jQuery获取网站的根网址 [英] Javascript/jQuery get root url of website
问题描述
我有网站:
http://www.example .com / folder1 / mywebsite / subfolder / page.html
该网站的根目录是: http://www.example.com/folder1/mywebsite
我想动态获取mywebsite的根网址。
如果我将这个网站发布到另一个地方,那么我不需要改变脚本。
I would like to get root url of "mywebsite" dynamicly. If I will publish this site to another place, then I will no need to change script.
例如: http://www.example.com/otherFolder/test/myChangedWebsite/subfolder/page.html
我会得到:
http://www.example.com/otherFolder/test/myChangedWebsite
我在page.htmljavascript:
var url = window.location.protocol +//+ window.location.host +'/otherPage.html
I tried in "page.html" javascript: var url = window.location.protocol + "//" + window.location.host + '/otherPage.html
但这只给我 http://www.example.com/otherPage.html 。
另外我知道location.origin,但这并不是所有浏览器都支持的,因为我发现在链接上: HTTP://www.w3sc hools.com/jsref/prop_loc_origin.asp
Also I know about location.origin but this is not supported for all browser as I found that on link: http://www.w3schools.com/jsref/prop_loc_origin.asp
如果可以用jQuery来完成,那也不错。
If it can be done with jQuery, it will be good as well.
推荐答案
这里有一个和Hawk's post相同的函数,只有很多很多:
Here's a function doing the same as Hawk's post above, only much, much shorter:
function getBaseUrl() {
var re = new RegExp(/^.*\//);
return re.exec(window.location.href);
}
详细信息: Javascript:获取基本网址或根网址
这篇关于Javascript / jQuery获取网站的根网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!