我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?


当前回答

这就是我如何使用它。

   window.location.replace('yourPage.aspx');   
   // If you're on root and redirection page is also on the root

   window.location.replace(window.location.host + '/subDirectory/yourPage.aspx');

   // If you're in sub directory and redirection page is also in some other sub directory.

其他回答

在我的工作经验中,JavaScript更好地重定向。

它取决于您想要如何更改位置. 如果您想在用户历史中登录您的网站,请使用 window.location.href='ur website';. 否则,如果您不登录历史,请使用 window.location.replace(“您的网站”);。

标准“瓦尼拉”JavaScript如何重新引导页面

window.location.href = 'newPage.html';

location.href = 'newPage.html';


以下部分适用于使用 HTTP_REFERER 作为许多安全措施之一(尽管这不是一个很好的保护措施)。如果您使用 Internet Explorer 8 或更低,这些变量在使用任何形式的 JavaScript 页面重定向(location.href 等)时会失去。

下面我们将实施一个替代 IE8 和更低,以免失去 HTTP_REFERER. 否则,你几乎总是可以简单地使用 window.location.href。

对 HTTP_REFERER 进行测试(URL 粘贴、会话等)可以帮助您知道请求是否合法(注:在评论中提到 drop 的链接中,还有一些方法可以工作周围 / 扫描这些引用器)


简单的跨浏览器测试解决方案(下载到 window.location.href for Internet Explorer 9+ 和所有其他浏览器)

使用:重定向(“anotherpage.aspx”);

function redirect (url) {
    var ua        = navigator.userAgent.toLowerCase(),
        isIE      = ua.indexOf('msie') !== -1,
        version   = parseInt(ua.substr(4, 2), 10);

    // Internet Explorer 8 and lower
    if (isIE && version < 9) {
        var link = document.createElement('a');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }

    // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
    else { 
        window.location.href = url; 
    }
}

下面是将代码转向另一个页面,时间为10秒。

<script>
    function Redirect()
    {
        window.location="http://www.adarshkr.com";
    }

    document.write("You will be redirected to a new page in 10 seconds.");
    setTimeout('Redirect()', 10000);
</script>

你也可以这样做,点击一个按钮使用 location.assign:

<input type="button" value="Load new document" onclick="newPage()">
<script>
    function newPage() {
        window.location.assign("http://www.adarshkr.com")
    }
</script>

但是,如果有人想重新引导到主页,那么他可以使用下面的剪辑。

window.location = window.location.host

如果你有三种不同的环境,如发展、排行和生产,这将是有用的。

您可以通过在 Chrome 控制台或 Firebug 的控制台中放置这些单词来探索此窗口或 window.location 对象。

使用 jQuery/JavaScript 方法重定向 HTML 页面

试试这个例子代码:

function YourJavaScriptFunction()
{
    var i = $('#login').val();
    if (i == 'login')
        window.location = "Login.php";
    else
        window.location = "Logout.php";
}

如果您想要提供一个完整的URL,如 window.location = “www.google.co.in”;