我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?


当前回答

警告:这个答案只是作为一个可能的解决方案提供;它显然不是最好的解决方案,因为它需要jQuery。

$(location).prop('href', 'http://stackoverflow.com')

其他回答

基本上,jQuery只是一个JavaScript框架,在这种情况下,你只能使用纯粹的JavaScript,所以在这种情况下,你有3个选项使用VanillaJavaScript:

使用位置替换,这将取代当前页面历史,这意味着无法使用后按钮返回原始页面。

window.location.replace("http://stackoverflow.com");

2) 使用位置指定,这将为您保存历史,并使用返回按钮,您可以返回原始页面:

window.location.assign("http://stackoverflow.com");

3)我建议使用上述方式之一,但这可能是使用纯粹的JavaScript的第三个选项:

window.location.href="http://stackoverflow.com";

您也可以在 jQuery 中编写一个函数来处理它,但不推荐,因为它只是一个线纯的JavaScript函数,如果您已经在窗口范围内,也可以使用上面的所有函数没有窗口,例如 window.location.replace(“http://stackoverflow.com”);可以是 location.replace(“http://stackoverflow.com”);

我在下面的图像中展示了所有这些:

此分類上一篇

有三种主要方法可以做到这一点,

window.location.href='blaah.com';
window.location.assign('blaah.com');

和...

window.location.replace('blaah.com');

最后一个是最好的,对于一个传统的重定向,因为它不会保存你去的页面,然后在你的搜索历史中重定向。

EDIT:窗口预定是可选的。

有很多方法可以做到这一点。

// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'

// window.history
window.history.back()
window.history.go(-1)

// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')


// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';

// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')

如何从客户端侧进行重定向:

<!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

您可以在 jQuery 中以以下方式重定向:

$(location).attr('href', 'http://yourPage.com/');