且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在输入id等于'submit'的情况下提交javascript

更新时间:2022-11-03 15:17:39

我能想到的唯一方法:

(function () {
    var method;

    window.submit = function (theForm) {
        if (!method) {
            method = document.createElement("form").submit;
        }

        method.call(theForm);
    };
}());

然后拨打提交(theFormYouWantToSubmit)

您可以在此处看到它: http:// jsfiddle.net/q68ky/2/

You can see it in action here: http://jsfiddle.net/q68ky/2/

编辑:提供一些解释,说明这一点....

此方法创建一个新的表单元素( document.createElement(form)),并存储对它的submit属性( method = document.createElement(form)。submit )。因为这是一个新创建的表单元素,没有子节点,我们可以保证submit属性实际上是我们需要的submit方法,而不是id / name为submit的子节点。

This method creates a new form element (document.createElement("form")), and stores a reference to the "submit" attribute of it (method = document.createElement("form").submit). Because this is a newly created form element, with no child nodes, we can guarantee that the "submit" attribute is actually the "submit" method we need, rather than a child node with an id/name of "submit".

然后我们使用 调用 方法( Function.prototype 的一部分),它设置将方法提交到我们想要提交的表单,而不是窗口对象,否则它就会出现。

We then use the call method (part of Function.prototype), which sets the context of the submit method to the form we want to submit, rather than the window object, which is what it would otherwise be on.

片段中的其余gubbins缓存了 submit 方法,因此所有这些(虽然很小)的开销都没有每次要提交表单时都会发生,并在本地范围内捕获缓存的方法,而不是将其保存在全局范围内并污染全局命名空间。

The rest of the gubbins in the snippet caches the submit method, so that all of this (albeit small) overhead does not take place every time you want to submit the form, and captures the cached method in a local scope, instead of holding it in the global scope and polluting the global namespace.