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


当前回答

在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/")

其他回答

试试这:

location.assign("http://www.google.com");

编码的例子。

警告:这个答案只是作为一个可能的解决方案提供;它显然不是最好的解决方案,因为它需要jQuery。

$(location).prop('href', 'http://stackoverflow.com')

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

<!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 代码重新引导页面或 URL

您甚至可以直接将 URL 转移到 attr() 方法,而不是使用变量。

第二条路

 window.location.href="http://stackoverflow.com";

你也可以编码如下(两者都是内部相同的):

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

第三种方式

第四条路

Location.assign() 方法将新文档上传到浏览器窗口中。

window.location.assign("http://stackoverflow.com"); 

第五条路

如 attr() 方法( jQuery 1.6 引入后)

var url = “http://stackoverflow.com”; $(位置)。prop('href', url);

标准“瓦尼拉”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; 
    }
}