我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
警告:这个答案只是作为一个可能的解决方案提供;它显然不是最好的解决方案,因为它需要jQuery。
$(location).prop('href', 'http://stackoverflow.com')
其他回答
您需要在代码中插入此行:
$(location).attr("href","http://stackoverflow.com");
如果您没有 jQuery,请使用 JavaScript:
window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");
一个不只是使用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";
使用 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");
此分類上一篇: https://jquery.com/browser-support/
<!DOCTYPE html>
<html>
<head>
<title>example</title>
</head>
<body>
<p>You will be redirected to google shortly.</p>
<script>
setTimeout(function(){
window.location.href="http://www.google.com"; // The URL that will be redirected too.
}, 3000); // The bigger the number the longer the delay.
</script>
</body>
</html>
不同选项如下:
window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL
window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"
您也可以使用 meta 数据进行页面重定向如下。
梅塔新鲜
<meta http-equiv="refresh" content="0;url=http://evil.example/" />
地图位置
<meta http-equiv="location" content="URL=http://evil.example" />
<base href="http://evil.example/" />
在此页面上可以找到许多其他方法将您的无疑客户端重新引导到他们可能不想去的页面(其中没有一个依赖于jQuery):
https://code.google.com/p/html5security/wiki/Redirection方法
您也可能被报告为恶意网站. 如果发生的话,当人们点击到您的网站的链接时,用户浏览器可能会警告他们您的网站是恶意的。
<!DOCTYPE html>
<html>
<head>
<title>Go Away</title>
</head>
<body>
<h1>Go Away</h1>
<script>
setTimeout(function(){
window.history.back();
}, 3000);
</script>
</body>
</html>
如果你将两页的例子结合在一起,你会有一个婴儿路由,这将保证你的用户永远不会想再使用你的网站。
如何从客户端侧进行重定向:
<!DOCTYPE html> <html> <head> <title>JavaScript and jQuery example to redirect a page or URL </title> </head> <body> <div id="redirect"> <h2>Redirect to another page</h2> </div> <script src="scripts/jquery-1.6.2.min.js"></script> <script> // JavaScript code to redirect a URL window.location.r