我如何将用户从一个页面转向另一个页面,使用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/")
其他回答
在 PHP、HTML 或 jQuery 部分后写下下面的代码,如果在 PHP 或 HTML 部分中间,则使用 <script> 标签。
location.href = "http://google.com"
有很多方法可以做到这一点。
// 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 = "http://www.example.com/";
这将记住前一页的历史,所以可以通过点击浏览器的背面按钮返回。
或:
window.location.replace("http://www.example.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”);
我在下面的图像中展示了所有这些:
此分類上一篇
JavaScript 的内容:
window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');
吉克里:
var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window