如何使用jQuery或纯JavaScript将用户从一个页面重定向到另一个页面?
<script type="text/javascript">
var url = "https://yourdomain.com";
// IE8 and lower fix
if (navigator.userAgent.match(/MSIE\s(?!9.0)/))
{
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
// All other browsers
else { window.location.replace(url); }
</script>
您可以在脚本部分如下编写Url.Action以处理按钮单击事件。
function onclick() {
location.href = '@Url.Action("Index", "Home")';
}
这非常容易实现。您可以使用:
window.location.href = "http://www.example.com/";
这将记住之前页面的历史记录,因此用户可以通过单击浏览器的返回按钮返回上一页。
或:
window.location.replace("http://www.example.com/");
这种方法不会记住上一页的历史记录。在这种情况下,后退按钮将被禁用。
如果您倾向于使用纯 JavaScript,我意识到使用 document.location.href = "https://example.com"
或 window.location.href = "https://example.com"
在 Firefox 中会导致兼容性问题。相反,请尝试使用:
location.href = "https://example.com";
location.replace("http://example.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>
您也可以通过单击按钮,使用location.assign来执行此操作:
<input type="button" value="Load new document" onclick="newPage()">
<script>
function newPage() {
window.location.assign("http://www.adarshkr.com")
}
</script>
单页应用程序,在同一应用程序路由内
window.location.pathname = '/stack';
JavaScript:
location.href = "http://stack.com";
window.location = "http://stack.com";
jQuery:
$(location).attr('href', "http://www.stack.com");
$(window).attr('location', "http://www.stack.com");
Angular 4
import { Router } from '@angular/router';
export class NavtabComponent{
constructor(private router: Router) {
}
this.router.navigate(['bookings/taxi']);
}
您可以使用:
window.location.replace("http://www.example.com/");
replace()
方法不会在会话历史中保存原始页面,因此用户无法使用后退按钮返回并再次重定向。注意:在这种情况下,浏览器的后退按钮将被禁用。
但是,如果您想要与单击链接相同的效果,则应选择:
window.location.href = "http://www.example.com/";
在这种情况下,浏览器的后退按钮将变为活动状态。
<script type="text/javascript">
if(window.location.href === "http://stackoverflow.com") {
window.location.replace("https://www.google.co.in/");
}
</script>
location.assign():
将一个路径传递给它以分配路由路径... Assign 会在分配路径后提供历史记录。
使用方法:应该向其传递值。
例如: location.assign("http://google.com")
location.href
可以把路径赋值给它,一旦设置完成,就会重定向到给定的路径,并保留历史记录...
使用方法:应该将值赋值给它。
例如: location.href = "http://google.com"
location.replace():
如果您不想保留历史记录,它将帮助您替换路径。一旦您替换了路径,它就不会再给您历史记录。
使用方法:应该向其传递值。
例如: location.replace("http://google.com")
assign()
和href
是相似的,两者都可以保留历史记录。 assign
通过传递值来工作,而 href 则通过赋值来工作。
您可以使用 JavaScript 自己实现它,而不必使用 jQuery 来分配。
window.location = "http://google.com"
location.href = "http://google.com"
你可以使用以下方式使用jQuery实现类似的效果。它将完全像上面那样执行相同的操作,
$(window).attr('location', "http://www.google.com");
$(location).attr('href', "http://www.google.com");
你可以轻松地理解两者之间的差异...使用:
function redirect(a) {
location = a
}
使用以下代码进行调用:redirect([url]);
location
后面不需要跟href
,因为这已经隐含在其中了。