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


当前回答

如果您想在同一应用程序中重新引导到路线

window.location.pathname = '/examplepath'

这将是走路的方式。

其他回答

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

您可以使用 jQuery 如下:

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

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

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

jQuery 不需要,你可以这样做:

window.open("URL","_self","","")

这是那么容易的!

启动 HTTP 请求的最佳方式是使用 document.loacation.href.replace(‘URL’)。

在您的点击功能上,只需添加:

window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
    window.location.href = "http://www.google.com";
});

原始问题:“如何使用 jQuery 重新引导?”,因此答案实施 jQuery >> 补充使用案例。


要重定向到使用JavaScript的页面:

window.location.href = "/contact/";

如果您需要延迟:

setTimeout(function () {
  window.location.href = "/contact/";
}, 2000);   // Time in milliseconds

jQuery 允许您轻松地从 Web 页面中选择元素. 您可以在页面上找到您想要的任何东西,然后使用 jQuery 添加特殊效果,对用户行动作出反应,或显示和隐藏您选择的元素内部或外部的内容。

$('a,img').on('click',function(e){
  e.preventDefault();
  $(this).animate({
    opacity: 0 //Put some CSS animation here
  }, 500);
  setTimeout(function(){
    // OK, finished jQuery staff, let's go redirect
    window.location.href = "/contact/";
  },500);
});

想象一下,有人写了一张10万行代码的脚本/插件,使用jQuery,你可以用一行或两行连接到这个代码。