我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
使用 JavaScript:
方法1:
window.location.href="http://google.com";
方法2:
window.location.replace("http://google.com");
使用 jQuery:
方法1: $(位置)
$(location).attr('href', 'http://google.com');
方法2:可重新使用的功能
jQuery.fn.redirectTo = function(url){
window.location.href = url;
}
jQuery(window).redirectTo("http://google.com");
其他回答
在 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>
您可以使用下面的方法重新引导页面:
使用头部中的 meta 标签 - <meta http-equiv="refresh" content="0;url=http://your-page-url.com" />. 请注意,内容="0;... 使用了几秒钟后你需要重新引导页面 使用 JavaScript: window.location.href = "http://your-page-url.com"; 使用 jQuery: $(location).attr('href', 'http://yourPage.com/');
您需要在代码中插入此行:
$(location).attr("href","http://stackoverflow.com");
如果您没有 jQuery,请使用 JavaScript:
window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");
它适用于每个浏览器:
window.location.href = 'your_url';
这就是我如何使用它。
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.