我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
使用 jQuery/JavaScript 重新引导用户
使用 jQuery 或 JavaScript 的位置对象,我们可以将用户转向另一个网页。
在 jQuery
将用户从一页转向另一页的代码是:
var url = 'http://www.example.com';
$(location).attr('href', url);
在JavaScript
将用户从一页转向另一页的代码是:
var url = 'http://www.example.com';
window.location.href = url;
或
var url = 'http://www.example.com';
window.location = url;
其他回答
var url = 'asdf.html';
window.location.href = url;
一个不只是使用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";
有三种主要方法可以做到这一点,
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')
在 PHP、HTML 或 jQuery 部分后写下下面的代码,如果在 PHP 或 HTML 部分中间,则使用 <script> 标签。
location.href = "http://google.com"
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 如何在JSON中使用杰克逊更改字段名
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?