为什么在提交按钮单击处理程序中提交表单覆盖设置location.href? [英] Why submitting a form overrides setting location.href in a submit button click handler?

查看:107
本文介绍了为什么在提交按钮单击处理程序中提交表单覆盖设置location.href?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题的灵感来自这篇文章

简而言之:为什么 window.location.href 在执行下面的代码时没有重定向到新页面(example.com)?

In a nutshell: Why window.location.href is not redirecting to a new page (example.com) when executing the code below?

<form>
    <input type="submit" id="submit" value="Submit">
</form>
<script>
    document.getElementById('submit').addEventListener('click', function (e) {
        window.location.href = "http://www.example.com";
    });
</script>

我一直相信,设置 window.location.href 立即加载新页面,但在这种情况下它不会。提交表单只是重新加载页面,设置新位置似乎完全被忽略。为什么?怎么样?我在这里缺少什么?

I've always believed, that setting window.location.href immediately loads a new page, but in this case it doesn't. Submitting the form just reloads the page instead, and setting a new location seems to be totally ignored. Why? How? What I'm missing here?

请注意,我知道在这种情况下如何防止表单提交的几种方法,我想知道,设置 location.href 的原因将被忽略。

Please notice, that I'm aware of several ways how to prevent form submitting in this case, rather I'd like to know, why setting location.href is ignored.

其他信息

这似乎发生在所有主流浏览器(Chrome,FF,IE11)中,但是当代码在Stack片段中运行时却不会发生。放入函数的 alert / console.log 显示,在 submit 之前执行click处理程序。

This seems to happen in all major browsers (Chrome, FF, IE11), but not when the code is run in a Stack snippet. An alert/console.log put in the function shows, that the click handler is executed before submit.

jsFiddle再现此问题。

推荐答案

如果您尝试更改位置,表示提交表单,您可以更加轻松地看到正在发生的事情

You can see easier here what is happening step by step if you will try tu change location drunning form submission

JSFIDDLE

如果您将检查浏览器网络选项卡,则可以通过重定向请求看到提交请求已取消(但仍然已发送)。我相信当你尝试这样做时会出现同样的情况 onclick onsubmit 第一个请求只是取消下一个请求阻止 window.location.href 重定向。

If you will check your browser network tab than you can see that the submit request is cancelled (but still sent) by redirect request. I believe that same situation occurs when you trying to do it onclick or onsubmit the first request just cancelling the next one and prevent window.location.href redirection.

这篇关于为什么在提交按钮单击处理程序中提交表单覆盖设置location.href?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆