Javascript 如何使用带有“this”的javascript提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12189791/
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 07:21:23  来源:igfitidea点击:

How to submit the form using javascript with "this"

javascriptformssubmit

提问by Sibu

Is there any way to submit the current form in which i have the href link like this

有什么方法可以提交我有这样的href链接的当前表单

<a href="javascript:;" onclick="this.submit();">Save</a>

I want to use same code evrywhere so i can't use any id or class

我想在任何地方使用相同的代码,所以我不能使用任何 id 或 class

回答by Sibu

Submit form using this.form.submit()

使用提交表单 this.form.submit()

i.e in your case it will be like

即在你的情况下它会像

<a href="#" onclick="this.form.submit();">Save</a>

But it highly recommended to use form name

但强烈建议使用表单名称

otherwise if you are comfortable using jquery you can also use jquery closestfunction

否则,如果你习惯使用 jquery,你也可以使用 jquery最接近的函数

$(field).closest("form").submit();

回答by Kernel James

<a href="" onclick="!function(a){while(a&&a.nodeName!="FORM")a=a.parentNode;if(a)a.submit();}(this);"></a>

回答by Ваня Антошкин

I use this solution for unknown form name:

我将此解决方案用于未知的表单名称:

function submitForm(originator)
{
    var pN=originator.parentNode;
    while (true)
    {
        if (pN&&pN.nodeName=='FORM')
        {
            pN.submit();
            break;
        }
        pN=pN.parentNode;
    }
}

and now on any document's object event we can use this function:

现在在任何文档的对象事件上我们都可以使用这个函数:

<div onclick="doSomething();submitForm(this)">test</div>

回答by un Artisan du Code

You can try this code

你可以试试这个代码

<a href="" onkeypress="submit(this.form)"/>
<script>
    function submit(form) {
        form.submit();
    }
</script>

回答by Lucas Green

What you want is:

你想要的是:

<a href="javascript:;"onclick="document.forms.<formname>.submit();">Save</a>

Actually it seems to work when <formname>is replaced with the form's id also.

实际上,当它<formname>也被表单的 id 替换时,它似乎也能工作。

Althoughy I would strongly recommend you research the practice known as Unobtrusive Javascript

尽管我强烈建议您研究称为Unobtrusive Javascript的实践

回答by Prasanth

Say you have nnumber of forms on your page. You can submit i+1th form by using:

假设您n的页面上有许多表单。您可以i+1使用以下方式提交表单:

document.forms[i].submit();

So if you have just one, and want to submit on link click,

所以如果你只有一个,并且想在链接点击时提交,

document.forms[0].submit();

should be your onclickattribute's value

应该是你的onclick属性值