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


当前回答

使用 location.replace() 将重定向您,但没有保存前一页的历史。

但是,如果你想保持你的历史,你必须使用 location.href=//path。

例子:

// Form with steps
document.getElementById('#next').onclick = function() {
   window.location.href='/step2' // Iteration of steps;
}

// Go to next step
document.getElementById('#back').onclick = function() {
   window.history.back();
}

// Finish
document.getElementById('#finish').onclick = function() {
   window.location.href = '/success';
}

// On success page
window.onload = function() {
    setTimeout(function() {
       window.location.replace('/home'); // I can't go back to success page by pressing the back button
    },3000);
}

其他回答

与 jQuery 合作:

$(window).attr("location", "http://google.fr");

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

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

这就是我如何使用它。

   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.

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

window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
    window.location.href = "http://www.google.com";
});
<script type="text/javascript">
    if(window.location.href === "http://stackoverflow.com") {      
         window.location.replace("https://www.google.co.in/");
       }
</script>