使用jQuery或纯 JavaScript 如何将用户从一页转到另一页?
当前回答
jj 用于重定向页面或 URL 的查询代码
第一路
这是用于重定向页面的 jQuery 代码 。 既然, 我已经把这个代码放在$( document). ready () 函数上, 一旦页面加载, 它将会立即执行 。
var url = "http://stackoverflow.com";
$(location).attr('href',url);
您甚至可以直接将一个 URL 直接传送到attr()方法,而不是使用变量。
第二路
window.location.href="http://stackoverflow.com";
您也可以使用这样的代码(两者在内部相同):
window.location="http://stackoverflow.com";
如果您对窗口. 位置和window.location.href
,然后你可以看到后一个设置href
明确表明财产,而前者默示地这样做。window.location
返回一个对象,该对象默认设置它.href
财产。
第三路
使用 JavaScript (JavaScript)replace()
方法方法的计算方法的计算方法window.location
对象。您可以将新的 URL 传送到replace()
方法, 它将模拟 HTTP 重定向。 顺便说一下, 记住window.location.replace()
方法不会在会话历史中放置原始页面, 这可能影响到后按钮的行为。 有时, 它会是你想要的, 所以要小心使用它 。
// Doesn't put originating page in history
window.location.replace("http://stackoverflow.com");
第四路
缩略location.assign()
方法在浏览器窗口中装入新文档。
window.location.assign("http://stackoverflow.com");
和(或)assign()
和replace()
方法为location.replace()
从文档历史中删除当前 URL 的方法,因此无法返回原始文档。您不能使用浏览器。后退按钮。如果您想要避免这种情况,应该使用location.assign()
方法,因为它在浏览器中装入一个新的文档。
第五路
类似attr()方法 (在 jQuery 1. 6 引入后)
var url = "http://stackoverflow.com";
$(location).prop('href', url);
其他回答
使用 :
function redirect(a) {
location = a
}
并称之为:redirect([url]);
没必要href
之后location
,因为它是隐含的。
您可以使用以下方法重定向页面:
通过在头部使用元标记 -
<meta http-equiv="refresh" content="0;url=http://your-page-url.com" />
注意:content="0;
... 用于在您需要多少秒后重定向页面使用 JavaScript :
window.location.href = "http://your-page-url.com";
使用 jQuery 查询 :
$(location).attr('href', 'http://yourPage.com/');
这是重定向到其他页面的代码 超过10秒的超时
<script>
function Redirect()
{
window.location="http://www.adarshkr.com";
}
document.write("You will be redirected to a new page in 10 seconds.");
setTimeout('Redirect()', 10000);
</script>
您也可以这样操作, 点击按钮时使用位置. 指派 :
<input type="button" value="Load new document" onclick="newPage()">
<script>
function newPage() {
window.location.assign("http://www.adarshkr.com")
}
</script>
您可以使用:
window.location.replace("http://www.example.com/");
缩略replace()
方法不会保存会话历史中的源页, 因此用户无法使用后端按钮返回, 然后再被重定向 。 注意: 在此情况下, 浏览器后端按钮将被禁用 。
但是,如果您想要与点击链接相同的效果,您应该选择:
window.location.href = "http://www.example.com/";
在此情况下, 浏览器后端按钮将激活 。
在 JavaScript 和 jQuery 中, 我们可以使用以下代码将一页改到另一页 :
window.location.href="http://google.com";
window.location.replace("page1.html");