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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5211328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:11:31  来源:igfitidea点击:

Clicking submit button of an HTML form by a Javascript code

javascriptbuttonautomationclicksubmit

提问by hkBattousai

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. The below is a condensed version of the original login code. How can I automatically click this submit button in this code?

我设法填写了表单字段,但不知道如何通过 JavaScript 单击提交按钮。以下是原始登录代码的精简版。如何在此代码中自动单击此提交按钮?

<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>

采纳答案by Matt Ball

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

or, use the same code as the onclickhandler:

或者,使用与onclick处理程序相同的代码:

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

(Though that onclickhandler is kind of stupidly-written: document.forms['loginForm']could be replaced with this.)

(虽然那个onclick处理程序写得有点愚蠢:document.forms['loginForm']可以用 替换this。)

回答by mercurial

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();

回答by krtek

You can do :

你可以做 :

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

But this won't call the onclickaction of your button, so you will need to call it by hand.

但这不会调用onclick按钮的操作,因此您需要手动调用它。

Be aware that you must use the nameof your form and not the idto access it.

请注意,您必须使用name表单的 而非id来访问它。