我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?
当前回答
您可以在 jQuery 中以以下方式重定向:
$(location).attr('href', 'http://yourPage.com/');
其他回答
这就是我如何使用它。
window.location.replace('yourPage.aspx');
// If you're on root and redirection page is also on the root
window.location.replace(window.location.host + '/subDirectory/yourPage.aspx');
// If you're in sub directory and redirection page is also in some other sub directory.
在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/")
您需要在代码中插入此行:
$(location).attr("href","http://stackoverflow.com");
如果您没有 jQuery,请使用 JavaScript:
window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");
在JavaScript中,您可以通过使用以下方式重新引导到一个特定的页面:
window.location.replace("http://www.test.com");
或
location.replace("http://www.test.com");
或
window.location.href = "http://www.test.com";
使用 jQuery:
$(window).attr("location","http://www.test.com");
原始问题:“如何使用 jQuery 重新引导?”,因此答案实施 jQuery >> 补充使用案例。
要重定向到使用JavaScript的页面:
window.location.href = "/contact/";
如果您需要延迟:
setTimeout(function () {
window.location.href = "/contact/";
}, 2000); // Time in milliseconds
jQuery 允许您轻松地从 Web 页面中选择元素. 您可以在页面上找到您想要的任何东西,然后使用 jQuery 添加特殊效果,对用户行动作出反应,或显示和隐藏您选择的元素内部或外部的内容。
$('a,img').on('click',function(e){
e.preventDefault();
$(this).animate({
opacity: 0 //Put some CSS animation here
}, 500);
setTimeout(function(){
// OK, finished jQuery staff, let's go redirect
window.location.href = "/contact/";
},500);
});
想象一下,有人写了一张10万行代码的脚本/插件,使用jQuery,你可以用一行或两行连接到这个代码。