我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
使用 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;
其他回答
如果你正在尝试生成包数据,有几个选项,你如何做到这一点,你可以生成单独的链接,每个页面你想能够直接到。
<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
});
});
一个不只是使用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";
<script type="text/javascript">
if(window.location.href === "http://stackoverflow.com") {
window.location.replace("https://www.google.co.in/");
}
</script>
在 jQuery 中,使用 $(位置)。attr('href', url):
$(document).ready(function(){ var url = "https://www.youtube.com/watch?v=JwMKRevYa_M"; $(location).attr('href', url); // 使用此 }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
在原始JavaScript中,有几种方法可以实现:
window.location.href="https://www.youtube.com/watch?v=JwMKRevYa_M";
href 属性明确设定。
window.location = "http://www.GameOfThrones.com";
因为 window.location 返回一个对象,默认设置其.href 属性。
window.location.replace("http://www.stackoverflow.com");
将现行窗口的位置替换为新窗口。
self.location = "http://www.somewebsite.com";
设置当前窗口本身的位置。
下面是JavaScript在一定时间(3秒)后重新引导的例子:
<script> setTimeout(函数() { window.location.href = “https://www.youtube.com/”; }, 3000); </script>
此分類上一篇: 你可以將延遲時間設定到你想要的任何地方:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Document Title</title>
<script type="text/javascript">
function delayer(delay) {
onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
}
</script>
</head>
<body>
<script>
delayer(8000)
</script>
<div>You will be redirected in 8 seconds!</div>
</body>
</html>