javascript 将基本网址重定向到主页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7481774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:15:33  来源:igfitidea点击:

Redirect base url to homepage

javascriptredirect

提问by Jorge

I need to find the base url and redirect it to the 'home' page. Also I need to use relative expressions so that I don't have to edit the js file and it could be used in diferent websites.

我需要找到基本 url 并将其重定向到“主页”页面。另外我需要使用相对表达式,这样我就不必编辑 js 文件,它可以在不同的网站中使用。

I'm using jquery and so far I have this:

我正在使用 jquery,到目前为止我有这个:

    if (location.host) {
    location.replace((location.host) + '/home');
    }

But is not working... I am new to js and I need help.

但不起作用......我是 js 的新手,我需要帮助。

回答by Fabrizio D'Ammassa

You could try this:

你可以试试这个:

window.location.href = "/home";

回答by Vinay Chittora

Well, you can just do this :

好吧,你可以这样做:

window.top.location.href = "/home";

It will automatically takes the domain and just adds the specified string and sets it. It works in all the browsers but its good to show an message like

它会自动获取域并添加指定的字符串并设置它。它适用于所有浏览器,但最好显示如下消息

The page will automatically redirect you to http://some.com/url/index.html, if it doesn't then click here.

该页面会自动将您重定向到http://some.com/url/index.html,如果没有,则单击此处

回答by Xavi López

Maybe you want to do window.location.replace(location.host + '/home');?

也许你想做什么window.location.replace(location.host + '/home');

Also, take a look at this question: How can I make a redirect page in jQuery?

另外,看看这个问题:How can I make a redirect page in jQuery?

回答by ephemer

I realise this is a very old question but maybe someone will stumble across it like I just did.

我意识到这是一个非常古老的问题,但也许有人会像我一样偶然发现它。

I'm pretty sure this is the answer the OP wanted:

我很确定这是 OP 想要的答案:

if (window.location.pathname === '/') {
  window.location.replace('/home');
}