我如何将用户从一个页面转向另一个页面,使用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重定向
jQuery 不需要, window.location.replace(...) 最好是模拟一个 HTTP 重定向。
window.location.replace(...) 比使用 window.location.href 更好,因为 replace() 不保留起源页面在会话历史中,这意味着用户不会陷入无止境后按钮故障。
如果你想模拟某人点击链接,使用 location.href
如果您想模拟一个 HTTP 重定向,请使用 location.replace。
例如:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
如果你正在尝试生成包数据,有几个选项,你如何做到这一点,你可以生成单独的链接,每个页面你想能够直接到。
<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...
请注意,示例中的当前页面在代码和CSS中以不同的方式处理。
如果您希望通过 AJAX 更改已支付的数据,这就是 jQuery 会进入的地方. 您所做的就是将一个点击处理器添加到相应不同页面的每个 anchor 标签. 这个点击处理器会引用一些 jQuery 代码,并通过 AJAX 获取下一个页面并更新新数据的表。
$(document).ready( function() {
$('a.pager-link').click( function() {
var page = $(this).attr('href').split(/\?/)[1];
$.ajax({
type: 'POST',
url: '/path-to-service',
data: page,
success: function(content) {
$('#myTable').html(content); // replace
}
});
return false; // to stop link
});
});
单页申请,在同一申请路线内
window.location.pathname = '/stack';
JavaScript 的内容:
location.href = "http://stack.com";
window.location = "http://stack.com";
jQuery:
$(location).attr('href', "http://www.stack.com");
$(window).attr('location', "http://www.stack.com");
角质4
import { Router } from '@angular/router';
export class NavtabComponent{
constructor(private router: Router) {
}
this.router.navigate(['bookings/taxi']);
}
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);
首先写得正确. 你想在一个应用程序内导航另一个链接从你的应用程序另一个链接. 这里是代码:
window.location.href = "http://www.google.com";
如果你想在你的应用程序内浏览页面,那么我也有代码,如果你愿意。