我有网站: http://www.example / folder1 / mywebsite / subfolder / page.html
该网站的根目录是: www.example/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.
例如: www.example/otherFolder/test/myChangedWebsite/subfolder/page.html
我会得到: www.example/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
但这只给我 www.example/otherPage.html 。
另外我知道location.origin,但这并不是所有浏览器都支持的,因为我发现在链接上: HTTP://www.w3sc hools/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: www.w3schools/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获取网站的根网址
发布评论