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


当前回答

我只是添加另一种方式:

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

<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>

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

其他回答

这就是我如何使用它。

   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.

使用 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;

它适用于每个浏览器:

window.location.href = 'your_url';

如何从客户端侧进行重定向:

<!DOCTYPE html> <html> <head> <title>JavaScript and jQuery example to redirect a page or URL </title> </head> <body> <div id="redirect"> <h2>Redirect to another page</h2> </div> <script src="scripts/jquery-1.6.2.min.js"></script> <script> // JavaScript code to redirect a URL window.location.r

您可以使用 jQuery 如下:

window.location = "http://yourdomain.com";

如果你只想要jQuery,那么你可以这样做:

$jq(window).attr("location","http://yourdomain.com");