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


当前回答

您可以使用下面的方法重新引导页面:

使用头部中的 meta 标签 - <meta http-equiv="refresh" content="0;url=http://your-page-url.com" />. 请注意,内容="0;... 使用了几秒钟后你需要重新引导页面 使用 JavaScript: window.location.href = "http://your-page-url.com"; 使用 jQuery: $(location).attr('href', 'http://yourPage.com/');

其他回答

首先写得正确. 你想在一个应用程序内导航另一个链接从你的应用程序另一个链接. 这里是代码:

window.location.href = "http://www.google.com";

如果你想在你的应用程序内浏览页面,那么我也有代码,如果你愿意。

使用 jQuery/JavaScript 重新引导用户

使用 jQuery 或 JavaScript 的位置对象,我们可以将用户转向另一个网页。

在 jQuery

将用户从一页转向另一页的代码是:

var url = 'http://www.example.com';
$(location).attr('href', url);

在JavaScript

将用户从一页转向另一页的代码是:

var url = 'http://www.example.com';
window.location.href = url;

var url = 'http://www.example.com';
window.location = url;

我只是添加另一种方式:

要将您的网站的任何特定页面/链接转向另一个页面,只需添加此代码行:

<script>
    if(window.location.href == 'old_url')
    {
        window.location.href="new_url";
    }

    // Another URL redirect
    if(window.location.href == 'old_url2')
    {
        window.location.href="new_url2";
    }
</script>

作为现实生活的例子,

<script>
    if(window.location.href == 'https://old-site.com')
    {
        window.location.href="https://new-site.com";
    }

    // Another URL redirect
    if(window.location.href == 'https://old-site.com/simple-post.html')
    {
        window.location.href="https://new-site.com/simple-post.html";
    }
</script>

使用这个简单的代码,您可以重新引导完整的网站或任何单页。

在JavaScript和jQuery中,我们使用以下代码重新引导页面:

window.location.href="http://google.com";
window.location.replace("page1.html");

但是,您可以在 jQuery 中创建一个功能,以重新引导页面:

jQuery.fn.redirect=function(url)
{
    window.location.href=url;
}

把这个功能称为:

jQuery(window).redirect("http://stackoverflow.com/")

有三种主要方法可以做到这一点,

window.location.href='blaah.com';
window.location.assign('blaah.com');

和...

window.location.replace('blaah.com');

最后一个是最好的,对于一个传统的重定向,因为它不会保存你去的页面,然后在你的搜索历史中重定向。

EDIT:窗口预定是可选的。