javascript 如果提交以编程方式启动,则不会触发提交事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18774821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:12:01  来源:igfitidea点击:

submit event does not fire if submit initiated programmatically

javascriptjqueryhtmlformsevent-handling

提问by Philipp Munin

I have a HTML form with button:

我有一个带按钮的 HTML 表单:

<form action="/" method="post" id="MyForm">
<input type="hidden" name="Field1" value="Value1" />
<input type="hidden" name="Field2" value="Value2" />
<input type="submit" name="name" value="submit" />
</form>

I have event handler for submit attached to Window:

我有用于提交附加到窗口的事件处理程序:

window.onsubmit = function()
{
    alert("Submit happening!");
};

This event handler fires properly if I click "Submit" button. However events never works when submit is triggered programmatically from javascript:

如果我单击“提交”按钮,此事件处理程序会正确触发。但是,当从 javascript 以编程方式触发提交时,事件永远不会起作用:

$("#MyForm")[0].submit();

How to catch submit event handler when it was initiated by Javascript, not by User click? I tried to subscribe for Form event using Jquery or AddEventListener - does not work.

如何捕获由 Javascript 启动的提交事件处理程序,而不是由用户点击?我尝试使用 Jquery 或 AddEventListener 订阅 Form 事件 - 不起作用。

回答by Prisoner

That's because you shouldn't just use the submitfunction, but triggerthe submit like:

那是因为你不应该只使用submit函数,而是trigger像这样提交:

$("#MyForm").trigger('submit');

回答by bfavaretto

Browsers don't fire the form's onsubmithandler when you manually call form.submit().

onsubmit当您手动调用时,浏览器不会触发表单的处理程序form.submit()

jQuery also mimicksused to mimick that (see this "wontfix" "bug" report).

jQuery 也模仿了过去的模仿(参见这个“wontfix”“bug”报告)。

See also:

也可以看看: