我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
试试这:
location.assign("http://www.google.com");
编码的例子。
其他回答
JavaScript 是非常广泛的. 如果你想跳到另一个页面,你有三个选项。
window.location.href='otherpage.com';
window.location.assign('otherpage.com');
//and...
window.location.replace('otherpage.com');
当你想移动到另一个页面,你可以使用其中一个,如果这是你的要求. 但是,所有三个选项都限于不同的情况。
如果你有兴趣了解更多关于这个概念,你可以通过更多。
window.location.href; // Returns the href (URL) of the current page
window.location.hostname; // Returns the domain name of the web host
window.location.pathname; // Returns the path and filename of the current page
window.location.protocol; // Returns the web protocol used (http: or https:)
window.location.assign; // Loads a new document
window.location.replace; // RReplace the current location with new one.
标准“瓦尼拉”JavaScript如何重新引导页面
window.location.href = 'newPage.html';
location.href = 'newPage.html';
以下部分适用于使用 HTTP_REFERER 作为许多安全措施之一(尽管这不是一个很好的保护措施)。如果您使用 Internet Explorer 8 或更低,这些变量在使用任何形式的 JavaScript 页面重定向(location.href 等)时会失去。
下面我们将实施一个替代 IE8 和更低,以免失去 HTTP_REFERER. 否则,你几乎总是可以简单地使用 window.location.href。
对 HTTP_REFERER 进行测试(URL 粘贴、会话等)可以帮助您知道请求是否合法(注:在评论中提到 drop 的链接中,还有一些方法可以工作周围 / 扫描这些引用器)
简单的跨浏览器测试解决方案(下载到 window.location.href for Internet Explorer 9+ 和所有其他浏览器)
使用:重定向(“anotherpage.aspx”);
function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
我已经使用JavaScript的重定向功能(),它工作了。
<script type="text/javascript">
$(function () {
//It's similar to HTTP redirect
window.location.replace("http://www.Technomark.in");
//It's similar to clicking on a link
window.location.href = "Http://www.Technomark.in";
})
</script>
使用 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");
因此,问题是如何创建一个重定向页面,而不是如何重定向到一个网站?
<script>
var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
if( url ) window.location.replace(url);
</script>
http://www.mywebsite.com/redirect?url=http://stackoverflow.com
如果你去那个链接,它会自动将你转向stackoverflow.com。
这就是你用JavaScript创建一个简单的重定向页面的方式。
我添加了 window.location.replace 在我的代码,因为我认为它适合一个重定向页面,但是,你必须知道,当使用 window.location.replace 和你得到重定向,当你按下后按钮在你的浏览器它不会回到重定向页面,它会回到页面之前,看看这个小演示事物。
例子:
因此,如果这符合您的需求,那么一切都应该顺利。 如果您想将重定向页面在浏览器历史中取代这个
if( url ) window.location.replace(url);
与
if( url ) window.location.href = url;