我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
在JavaScript和jQuery中,我们使用以下代码重新引导页面:
window.location.href="http://google.com";
window.location.replace("page1.html");
但是,您可以在 jQuery 中创建一个功能,以重新引导页面:
jQuery.fn.redirect=function(url)
{
window.location.href=url;
}
把这个功能称为:
jQuery(window).redirect("http://stackoverflow.com/")
其他回答
您可以使用 window.location 设置。
例子:
window.location = "https://stackoverflow.com/";
此分類上一篇: 我如何轉向另一個網站?
我只是添加另一种方式:
要将您的网站的任何特定页面/链接转向另一个页面,只需添加此代码行:
<script>
if(window.location.href == 'old_url')
{
window.location.href="new_url";
}
// Another URL redirect
if(window.location.href == 'old_url2')
{
window.location.href="new_url2";
}
</script>
作为现实生活的例子,
<script>
if(window.location.href == 'https://old-site.com')
{
window.location.href="https://new-site.com";
}
// Another URL redirect
if(window.location.href == 'https://old-site.com/simple-post.html')
{
window.location.href="https://new-site.com/simple-post.html";
}
</script>
使用这个简单的代码,您可以重新引导完整的网站或任何单页。
使用 location.replace() 将重定向您,但没有保存前一页的历史。
但是,如果你想保持你的历史,你必须使用 location.href=//path。
例子:
// Form with steps
document.getElementById('#next').onclick = function() {
window.location.href='/step2' // Iteration of steps;
}
// Go to next step
document.getElementById('#back').onclick = function() {
window.history.back();
}
// Finish
document.getElementById('#finish').onclick = function() {
window.location.href = '/success';
}
// On success page
window.onload = function() {
setTimeout(function() {
window.location.replace('/home'); // I can't go back to success page by pressing the back button
},3000);
}
有三种主要方法可以做到这一点,
window.location.href='blaah.com';
window.location.assign('blaah.com');
和...
window.location.replace('blaah.com');
最后一个是最好的,对于一个传统的重定向,因为它不会保存你去的页面,然后在你的搜索历史中重定向。
EDIT:窗口预定是可选的。
如果您更喜欢使用纯粹的JavaScript,我意识到使用document.location.href = “https://example.com” 或 window.location.href = “https://example.com” 会导致 Firefox 中的兼容性问题。
location.href = "https://example.com";
location.replace("http://example.com");
在我看来,这个问题已经解决了,祝你好运!
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 如何在JSON中使用杰克逊更改字段名
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象