javascript - 页面加载 jQuery 表单提交不起作用

标签 javascript jquery post pageload

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                submitForm($("#login-user-one"));
            });

            function submitForm(form) {
                console.log($(form).attr("method"));
                $(form).submit();
            };
        </script>
    </head>
    <body>
        <form id="login-user-one" name="login" method="POST" action="/test.html">
            <input name="userid" tabindex="1" value="MyUser">
            <input name="pass" type="password" tabindex="2" value="MyPass">
            <input type="submit" name="submit" value="1" tabindex="3">
        </form>
    </body>
</html>

我不明白为什么上面的方法不起作用。日志显示了 POST 的值,但它不会提交。控制台没有错误。

JS fiddle :https://jsfiddle.net/t48hk9qx/

最佳答案

嗯,这对我来说是新的。

因为您的表单有一个带有 name="submit" 的命名元素,该元素引用将替换 HTMLFormElement.prototype.submit()功能。

来自documentation ...

Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's action HTML attribute).

jQuery 尝试在以编程方式提交表单时执行该函数,例如

if (typeof element.submit === 'function') {
  element.submit()
}

但在您的情况下,element.submit 是一个 HTMLInputElement

快速简便的解决方案,重命名您的 submit 元素,或者像在单按钮表单中更常见的那样,只需删除 name 属性。


如果您必须保留名为“submit” 的提交按钮,这似乎可行

function submitForm(form) {
  // note, "form" is already a jQuery object
  console.log(form.attr("method"));

  HTMLFormElement.prototype.submit.call(form[0])
}

关于javascript - 页面加载 jQuery 表单提交不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55152307/

相关文章:

javascript - 如何使用 javascript 书签点击网站的元素?

php - Facebook API - 帖子未出现在群组中

javascript - tr 元素不可点击吗?

javascript - jQuery 选择包含最少文本字符数的段落

swift - 向谷歌表单发出 POST 请求

php - 如何将用户创建的内容保存为 URL(哈希)参数?

javascript - AVA + React-Native 的测试配置

javascript - 使用 vuejs 而不使用指令的域特定语言

javascript - 蓝色窗口在 3 秒后消失

javascript - leaflet展开控制和autoZindex