使用 submit() 从链接提交的表单无法被 onsubmit 处理程序捕获
很惊讶,我在从 JS 提交表单时遇到了这个奇怪的问题.
Surprised, I am encountering this weird issue while submitting form from JS.
考虑一个使用 submit
按钮和 anchor link
Consider a simple form submitted using two ways from a submit
button and an anchor link
<form method="POST" action="page.html" name="foobar" id="test">
<input type="text" />
<input type="submit" />
</form>
<a href="#" onclick="document.getElementById('test').submit();">click me</a>
捕获提交事件的函数
document.getElementById('test').onsubmit = function() {
// Same result with
// * document.foobar.onsubmit
// * document.forms['foobar'].onsubmit
alert('foobar');
return false;
}
现在,当通过单击 submit
按钮提交表单时,我会收到警报,但 单击链接时不会.为什么会这样?
Now, when the form is submitted from clicking the submit
button I get the alert, but not when clicking the link. Why is this doing so?
小提琴显示问题
推荐答案
为了提供一个合理确定的答案,HTML 表单提交算法 第 5 项指出,表单仅在未提交时才调度提交事件通过调用提交方法(这意味着它仅在通过按钮或其他隐式方法提交时才调度提交事件,例如在焦点位于输入类型文本元素上时按 Enter).
To provide a reasonably definitive answer, the HTML Form Submission Algorithm item 5 states that a form only dispatches a submit event if it was not submitted by calling the submit method (which means it only dispatches a submit event if submitted by a button or other implicit method, e.g. pressing enter while focus is on an input type text element).
如果没有发送提交事件,则不会调用提交处理程序.
If no submit event is dispatched, then the submit handler won't be called.
这与 DOM 2 HTML 不同规范,它说提交方法应该做提交按钮所做的事情.
That is different to the DOM 2 HTML specification, which said that the submit method should do what the submit button does.
所以如果你想使用脚本提交表单,你应该手动调用提交监听器.如果侦听器是使用 addEventListener 添加的,那么您需要记住并调用它,因为您无法通过检查表单来发现它(如下所示).
So if you want to use script to submit a form, you should manually call the submit listener. If the listener was added using addEventListener, then you'll need to remember that and to call it since you can't discover it by inspecting the form (as suggested below).
如果监听器是内联设置的,或者添加到 DOM onsubmit 属性中,你可以这样做:
If the listener is set inline, or added to the DOM onsubmit property, you can do something like:
<form onsubmit="return validate(this);" ...>
...
</form>
<button onclick="doSubmit()">submit form</button>
<script>
function doSubmit() {
var form = document.forms[0];
if (form.onsubmit) {
var result = form.onsubmit.call(form);
}
if (result !== false) {
form.submit();
}
}
</script>
如果您需要传递参数或做其他事情,生活会更加艰难.
Life is tougher if you need to pass parameters or do other things.
相关文章