使用javascript触发表单提交 [英] Trigger form submission with javascript

查看:84
本文介绍了使用javascript触发表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,我想通过JavaScript提交。显然,这可以通过以下方式实现:

I have a form that I would like to submit via JavaScript. Obviously this can be achieved by:

document.getElementById("myForm").submit();

问题是我在提交了一个监听器事件看起来像这样:

The issue is that I have a listener on the submit event that looks like this:

document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault();
    // Other work
});

当我调用 .submit()时,不会触发此事件处理程序。来自 MDN



Gecko-调用此方法时,不会触发表单的onsubmit事件处理程序(例如,onsubmit =return
false;)基础申请。一般情况下,不保证HTML用户代理调用

The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.

所以,考虑到这种限制,怎么能我以确保调用事件处理程序的方式提交表单?

So, given this restraint, how can I submit the form in a way that ensures the event handler is invoked?

推荐答案

您需要创建一个提交事件,然后发送它。

You need create a submit event, then dispatch it.

(function () {
              if ( typeof window.CustomEvent === "function" ) return false;

              function CustomEvent ( event, params ) {
                params = params || { bubbles: true, cancelable: true, detail: undefined };
                var evt = document.createEvent('submit');
                evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
                return evt;
               }

              CustomEvent.prototype = window.Event.prototype;

              window.CustomEvent = CustomEvent;

})();
var evt = new CustomEvent("submit", {"bubbles":true, "cancelable": true});
document.getElementById("myForm").addEventListener("submit",function(event) {
                event.preventDefault();
                alert('submit');
});

然后,当您想要提交此功能时,您需要致电:

Then when you want submit this function you need to call:

!document.getElementById("myForm").dispatchEvent(evt);

有关更多活动信息,请参阅 dispatchEvent。

For more event info see dispatchEvent.

这篇关于使用javascript触发表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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