如果提交以编程方式启动,则提交事件不会触发
我有一个带有按钮的 HTML 表单:
I have a HTML form with button:
<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!");
};
如果我单击提交"按钮,此事件处理程序会正确触发.但是,当从 javascript 以编程方式触发提交时,事件永远不会起作用:
This event handler fires properly if I click "Submit" button. However events never works when submit is triggered programmatically from javascript:
$("#MyForm")[0].submit();
当提交事件处理程序由 Javascript 启动时,如何捕获它,而不是通过用户点击?我尝试使用 Jquery 或 AddEventListener 订阅 Form 事件 - 不起作用.
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.
推荐答案
那是因为你不应该只使用 submit
函数,而是 trigger
提交如下:
That's because you shouldn't just use the submit
function, but trigger
the submit like:
$("#MyForm").trigger('submit');
相关文章