简体   繁体   English

通过 Javascript 代码单击 HTML 表单的提交按钮

[英]Clicking submit button of an HTML form by a Javascript code

I don't know much about WEB probramming, so feel free to ask if I'm missing any details.我对 WEB probramming 不太了解,所以请随时询问我是否遗漏了任何细节。

There is a certain website which I'm visiting very frequently, and it requires users to log in every time they visit.有一个我经常访问的网站,它要求用户每次访问时都登录。 For the login page of this website, I'm trying to write down a userscript which will automatically log me in.对于这个网站的登录页面,我试图写下一个用户脚本,它会自动让我登录。

I managed to fill in the form fields, but don't have any idea how to click the submit button by JavaScript.我设法填写了表单字段,但不知道如何通过 JavaScript 单击提交按钮。 The below is a condensed version of the original login code.以下是原始登录代码的精简版。 How can I automatically click this submit button in this code?如何在此代码中自动单击此提交按钮?

<div id="start">
    <div id="header">
        <div id="login">
            <form id="loginForm" name="loginForm" method="post" action="#">
                // ...
                <input type="submit" id="loginSubmit" onclick="changeAction('submitInput','loginForm');document.forms['loginForm'].submit();" value="Log in" />
                // ...
            </form>
        </div>
    </div>
</div>

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.通常提交表单的常用方法是在表单本身上调用 submit() ,如 krtek 的回答中所述。

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:但是,如果您出于某种原因需要实际单击提交按钮(您的代码取决于提交按钮的名称/值或其他内容),您可以像这样单击提交按钮本身:

document.getElementById('loginSubmit').click();
document.getElementById('loginSubmit').submit();

or, use the same code as the onclick handler:或者,使用与onclick处理程序相同的代码:

changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();

(Though that onclick handler is kind of stupidly-written: document.forms['loginForm'] could be replaced with this .) (虽然onclick处理程序写得有点愚蠢: document.forms['loginForm']可以用this替换。)

You can do :你可以做 :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.但这不会调用按钮的onclick操作,因此您需要手动调用它。

Be aware that you must use the name of your form and not the id to access it.请注意,您必须使用表单的name而不是id来访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM