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


当前回答

在我的工作经验中,JavaScript更好地重定向。

它取决于您想要如何更改位置. 如果您想在用户历史中登录您的网站,请使用 window.location.href='ur website';. 否则,如果您不登录历史,请使用 window.location.replace(“您的网站”);。

其他回答

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

// 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')

它适用于每个浏览器:

window.location.href = 'your_url';

因此,问题是如何创建一个重定向页面,而不是如何重定向到一个网站?

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

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

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

如果您更喜欢使用纯粹的JavaScript,我意识到使用document.location.href = “https://example.com” 或 window.location.href = “https://example.com” 会导致 Firefox 中的兼容性问题。

location.href = "https://example.com";
location.replace("http://example.com");

在我看来,这个问题已经解决了,祝你好运!